Axios get a file from URL and upload to s3

和自甴很熟 提交于 2021-01-28 07:19:30

问题


I'm trying to get files from a site using axios.get, and then uploading it directly to S3. However, the files are corrupted or not encoded properly, and can't be opened after upload. File types range from .jpg, .png to .pdf. Here is my code:

axios.get(URL, {
  responseEncoding: 'binary',
  responseType: 'document',
}).then((response) => {
  return new Promise((resolve, reject) => {
    const s3Bucket = nconf.get('AWS_S3_BUCKET');

    s3.upload({
      'ACL': 'public-read',
      'Body': response.data,
      'Bucket': s3Bucket,
      'Key': `static/${filePath}/${fileManaged.get('filename')}`,
    }, function(err) {
      if (err) {
        return reject(err);
      }
    });
  });
});

I've tried modifying responseType to arraybuffer and creating a buffer using Buffer.from(response.data, 'binary').toString('base64'), to no avail. What am I missing?


回答1:


I was able to get it working by using an arraybuffer and the .putObject function instead of .upload

axios.get(encodeURI(url), {
  responseType: 'arraybuffer',
}).then((response) => {
s3.putObject({
  'ACL': 'public-read',
  'Body': response.data,
  'Bucket': s3Bucket,
  'Key': `static/${filePath}/${fileManaged.get('filename')}`,
} function(err) {



回答2:


Axios encodes the response body in utf8.
You should use other library like request.



来源:https://stackoverflow.com/questions/61605078/axios-get-a-file-from-url-and-upload-to-s3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!