LoginSignup
1
0

More than 3 years have passed since last update.

serverless-http で画像 ( image ) や pdf などの binary を返す

Last updated at Posted at 2019-11-29

追記 2020-01-09

第二引数で渡せます。

const fs = require('fs')
const path = require('path')
const serverless = require('serverless-http')
const app = require('express')()
app.get('/file.pdf', (req, res, next) => {
  res.setHeader('Content-Type', 'application/pdf')
  fs.createReadStream(path.join(__dirname, 'file.pdf')).pipe(res)
})

const binaryMimeTypes = [
    'application/pdf',
]

const proxy = serverless(app, { binary: binaryMimeTypes })
//                              ^ オプションで渡せる
export const handler = proxy

コードへの記述

serverless-http は環境変数 BINARY_CONTENT_TYPES見ているので下記のように書けば動くと思います。

process.env.BINARY_CONTENT_TYPES = ['application/pdf'].join(',')

const fs = require('fs')
const path = require('path')
const serverless = require('serverless-http')
const app = require('express')()
app.get('/file.pdf', (req, res, next) => {
  res.setHeader('Content-Type', 'application/pdf')
  fs.createReadStream(path.join(__dirname, 'file.pdf')).pipe(res)
})
exports.handler = serverless(app)

AWS Gateway の設定の変更も必要

AWS Gateway の設定の変更も必要ですのでこちらの記事を参考にしてください。

AWS Gateway の設定を Swagger でやっている場合トップレベルに下記を追加します

x-amazon-apigateway-binary-media-types:
  - '*/*'

serverless-http が内部でやってること

lambda はバイナリを返せません。
なので base64 エンコードして「エンコード済だよ」と AWS Gateway に伝えます。

こちらの記事が参考になります。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0