使用Node JS从AWS lambda函数在S3上上传图像

时间:2019-04-19 13:55:32

标签: node.js amazon-s3 aws-lambda aws-sdk aws-sdk-nodejs

我正在尝试使用节点JS在AWS lambda函数上将图像从Ajax上传到S3,但是图像已损坏。我的代码如下。

客户端:

var formData = new FormData();
formData.append('file', e.target.files[0]);
formData.append('operation', 'uploadImage');
$.ajax({
    type: 'post',
    url: 'AWS-API-Gateway-URL-here',
    processData: false,
    contentType: false,
    dataType: 'json',
    data: formData
}).done(function (response) {            

}.bind(this)).always(function () {
});

NodeJS中的以下Lambda函数代码:

const getContentType = event => {
  const contentType = event.headers["content-type"];
  if (!contentType) {
    return event.headers["Content-Type"];
  }
  return contentType;
};

解析器功能:

const parser = (event) => new Promise((resolve, reject) => {
  const busboy = new Busboy({
      headers: {
          'content-type': getContentType(event)
      }
  });

  const result = {};

  busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
      file.on('data', data => {
          result.file = data;
      });

      file.on('end', () => {
          result.filename = filename;
          result.contentType = mimetype;
      });
  });

  busboy.on('field', (fieldname, value) => {
      result[fieldname] = value;
  });

  busboy.on('error', error => reject(error));
  busboy.on('finish', () => {
      event.body = result;
      resolve(event);
  });

  busboy.write(event.body, event.isBase64Encoded ? 'base64' : 'binary');
  busboy.end();
});

图片上传功能:

const uploadPropertyImage = (buffer, fileName) => 
  new Promise((resolve, reject) => {
    const bucketName = "BUCKET-NAME";
    var filePath = `${fileName}`;
    const data = {
      Bucket: bucketName,
      Key: filePath,
      Body: buffer,
      ACL: 'public-read',
    };
    s3.upload(data, (error, data) => {
       if (!error) {
          resolve(data.Location);
       } else {
          reject(new Error("error during put"));
       }
    });
  });

从AWS处理程序中调用解析器函数:

parser(event).then(() => {
      var request = event.body;
      if (request.operation == "uploadImage") {
        uploadPropertyImage(request.file, request.filename)
           .then((result) => { 
            // handles succesfull upload
        }).catch(() => {
            // error
        });
      }
    });

我的图像正在上传,但是上传的图像已损坏。请帮忙。

1 个答案:

答案 0 :(得分:0)

我增加了内存数量,而且似乎可以正常工作。...我确定我之前曾尝试过此方法,但谁知道呢。我知道了更多。