Amazon Lambda - Node.js - файл Docx загружен как поврежденный - PullRequest
0 голосов
/ 05 ноября 2019

Я конвертирую html в docx в лямбда-функции AWS. После преобразования в docx я хочу загрузить его в виде файла и отправить в ответ в виде вложения. Но я не могу скачать правильный файл. Всякий раз, когда я достигаю конечной точки. Файл загружен, но он поврежден.

файл примера загрузки файла


function htmlToDoc(html) {
  const docx = require('html-docx-js').asBlob(html, {
    orientation: 'portrait',
    margins: {
      top: 3.17 * 567,
      right: 1.9 * 567,
      bottom: 1.9 * 567,
      left: 1.9 * 567,
      header: 720 * 567,
      footer: 1.27 * 567,
      gutter: 0
    }
  });

  return docx;
}


module.exports.handler = (event, context, callback) => {

  try {
    const html = `
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Example file</title>
</head>

<body>
  All example content goes here
</body>
</html>`;

    Promise.resolve(true)
      .then(() => {
        console.log(html) // It is printing correct html here
        return htmlToDoc(html);
      })
      .then((docx) => {
        return callback(null, {
          statusCode: 200,
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': true,
            'Content-type':
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'Content-Disposition': 'attachment; filename="report.docx"'
          },
          isBase64Encoded: true,
          body: Buffer.from(docx).toString('base64')
        });
      });
  } catch (error) {
    console.log('error 1', error);
    return createErrorResponse(500);
  }
};

Serverless.yml

service: example-file-downalod

provider:
  stage: ${opt:stage, 'dev'}
  name: aws
  runtime: nodejs10.x
  region: ${file(env.yml):${self:provider.stage}.REGION}
  config: ${file(env.yml):${self:provider.stage}}
  memorySize: 256
  timeout: 30
  versionFunctions: false
  apiGateway:
    binaryMediaTypes:
      - '*/*'
  environment:
    STAGE: ${self:provider.stage}

package:
  individually: true

plugins:
  - serverless-apigw-binary
  - serverless-apigwy-binary

custom:
  apigwBinary:
    types:           #list of mime-types
      - 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

  exampleFileDownalod:
    handler: src/example-file-download.handler
    events:
      - http:
          path: example-file-download-new/{jobId}
          method: get
          contentHandling: CONVERT_TO_BINARY
          request:
            parameters:
              paths:
                jobId: true
          cors:
            origin: ${self:provider.config.ORIGIN}
            headers:
              - Content-Type
              - Content-Disposition
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token
              - X-Amz-User-Agent
              - Access-Control-Allow-Origin
              - Access-Control-Allow-Credentials
              - Access-Control-Allow-Methods
              - Access-Control-Allow-Headers
              - Cache-Control
              - Cookie
            allowCredentials: true
          contentHandling: CONVERT_TO_BINARY

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...