繁体   English   中英

使用Node JS从AWS lambda函数上载S3上的映像

[英]Uploading an image on S3 from AWS lambda function using Node JS

我正在尝试使用节点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
        });
      }
    });

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM