我正在AWS Lambda函数中将html转换为docx。将其转换为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