【问题标题】:Image file getting corrupted on uploading to amazon s3 public bucket using reactjs使用 reactjs 上传到 amazon s3 公共存储桶时图像文件损坏
【发布时间】:2018-06-06 19:17:45
【问题描述】:

我正在尝试使用 reactjs 上传图像,但图像在上传到 amazon s3 时已损坏。 代码如下。

uploadToS3 = (imageUri, fileName, fileType, file,success, failure) => {
    let body    = new FormData();
    let url=imageServer+fileName;
    body.append('key', fileName);
    body.append('acl', 'public-read');
    body.append('Content-Type', 'multipart/form-data');
    body.append('Content-Disposition', 'inline');
    body.append('file', {
      name: 'file',
      uri: imageUri,
      type: file.type
    });
    return axios.post(imageServer,body,
    { headers: {
        'Accept':file.type,
        'Content-Type':file.type,
      }}
    ).then(response => {
      console.log('[AWS S3] Response ==> ', response)
      this.props.addNewImage(url,this.props.arrayname);
      return response;
    }).catch(error => {
      console.log('[AWS S3] Error ==> ', error)
      return error;
    })
  }

【问题讨论】:

  • 文件到达 S3 时是否正确命名?到了 S3 是大还是小?
  • @KMo 是的,当我在 amazon s3 中看到该文件时,该文件的命名绝对正确。但它已损坏!!请帮忙!
  • 您要发送的文件与 S3 中的文件大小有什么区别?
  • 文件大小只有15字节,而实际大小要大得多
  • 看起来您实际上并未将文件作为“正文”的一部分正确上传。你是从网络浏览器测试这个吗?您可以签入开发人员工具以查看您发送的有效负载。

标签: reactjs amazon-web-services amazon-s3


【解决方案1】:

实际上我犯的错误是在formData对象中为'file'对象发送了错误的值。正确的代码如下-

uploadToS3 = (imageUri, fileName, fileType, file,success, failure) => {
    let body    = new FormData();
    let url=imageServer+fileName;
    body.append('acl', 'public-read');
    body.append('Content-Type',file.type);
    body.append('key', fileName);
    body.append('file',file);

   return axios.post(imageServer,body)
    .then(response => {
      console.log('[AWS S3] Response ==> ', response)
      this.props.addNewImage(url,this.props.arrayname);
      return response;
    }).catch(error => {
      console.log('[AWS S3] Error ==> ', error)
      return error;
    })
  }


_handleImageChange(e){
    let reader = new FileReader();
    let file = e.target.files[0];
    console.log(file,'file');
    reader.onloadend = () => {
      let uri=reader.result;
      let fileType = /^data:image\/\w+;/.exec(reader.result)[0].replace(/^data:image/,"").replace("/","").replace(";","");
      let fileName='img'+`${new Date().getTime()}`+'.'+fileType;
      console.log("filename",fileName);
      this.uploadToS3(uri,fileName,fileType,file);     
    }
    reader.readAsDataURL(file);
  }

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 2018-12-30
    • 2014-01-27
    • 2023-02-04
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2015-05-05
    相关资源
    最近更新 更多