首页 > 解决方案 > 使用 AWS Lambda 函数导出具有内容处置的 Docx 文件

问题描述

我正在编写一个处理程序作为 AWS Lambda 函数,它应该将内容包装到 docx 文件中。我在响应标头中使用 Content-Disposition 以实现目标。以下是我到目前为止编写的代码:

//Process Array Buffer and extract the plain content out of it
export const extractContent = async (data: Buffer) => {
  return new Promise((resolve, reject) => 
    textract.fromBufferWithMime(
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      data,
      { preserveLineBreaks: true },
      (err, content) => {
        if (err) {
          reject(err);
        } else {
          resolve(content);
        }
      }
    )
  );
};

export const handlerName = async (
  event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
  if (event.body === null) {
    return ErrorResponse;
  }
  const result = await class.func(JSON.parse(event.body)); //returns an array buffer object
  if (result instanceof Error) {
    return ErrorResponse;
  }
  const content = await extractContent(result.data)
          .then(res => res)
          .catch(err => err);
  const headers = {
    "Access-Control-Allow-Origin": "*",
    "Strict-Transport-Security": "'max-age=31536000'",
    "Access-Control-Expose-Headers": "Content-Disposition",
    "Content-Disposition": attachment; filename=fn.docx; filename*=UTF-8''fn.docx,
    "Content-Type": "application/vnd.ms-word.document" 
  };
  return {
    body: content,
    headers,
    statusCode: 200,
  };
};

现在 APIGatewayResponse 中只能返回字符串;因此我无法返回字节对象 | 流 | 而是缓冲。我可以下载 docx 文件,但它没有在 MS-Word 中打开;我总是收到一个详细的错误,即文件已损坏或某些部分无效或丢失。

我已经尝试过 base64 编码的字符串,但仍然无法获得所需的内容。请提出解决方案。

我使用 SLS 框架在 typescript Node 中编写处理程序。

标签: node.jstypescriptaws-lambdaserverless-framework

解决方案


推荐阅读