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



我正在尝试使用节点JS将图像从Ajax上传到AWS lambda函数上的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
        });
      }
    });

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

我已经提高了内存计数,它似乎正在工作......我确定我以前尝试过这个,但谁知道呢。更多,因为我得到了它。

相关内容

  • 没有找到相关文章

最新更新