Docx Document Serverless S3 Error while Putobject

2019-08-21 02:36发布

问题:

I am stuck in a situation for a long time. I am trying to upload a docx file to S3 bucket , using Serverless framework

I was successful in uploading the docx document to S3 bucket.But what happened is, when I opened the document from S3. The document contained a buffer data converted to base64 string. i.e the big string about 23 pages.

The docx was corrupted.

MY Code

exports.putFile = async(event) =>{
  try {
    var bitmap = fs.readFileSync('./test.docx');
    let bufferValue = new Buffer(bitmap).toString('base64');
    const valueFromBucket = await S3.putObject(
        { Body: bufferValue, 
          Bucket: '********', 
          Key: '*****.docx',
          ContentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          ContentDisposition: 'attachment',
          ContentEncoding: 'base64'
          }).promise();
    return{
      statusCode: 200,
      body: JSON.stringify(valueFromBucket)
    }
  }catch(err){
    return {
      statusCode: err.statusCode || 400,
      body: err.message || JSON.stringify(err.message)
    }
  }
}

Serverless.yml

service: node11

custom:
  bucket: ******

provider:
  name: aws
  runtime: provided # set to provided
  stage: dev
  region: *****
  iamRoleStatements:
    - Effect: Allow
      Action:
        - s3:*
        - ses:SendEmail
        - ses:SendRawEmail
      Resource: "*"

functions:
  hello:
    handler: handler.*****
    memorySize: 1024
    events:
      - http:
          path: /
          method: get
    layers: # add layer
      - arn:aws:lambda:us-east-1:553035198032:layer:nodejs11:3
  putFile:
    handler: handler.*****
    description: put Object using S3 service.
    memorySize: 1024
    timeout: 5
    events:
      - http:
          path: putfile
          method: post
          integration: lambda
          cors: true
    layers: # add layer
      - arn:aws:lambda:us-east-1:553035198032:layer:nodejs11:3

I think the code is almost working , but this issue of the base 64 string which is contained in the uploaded document is the issue.

Any kind of help appreciated, Thanks in advance

回答1:

It should not be necessary to convert the binary buffer to string before uploading. Drop the .toString('base64'), everything else ought to work.