使用react-native-fs上传到AWS S3时图像损坏

时间:2019-05-24 20:42:35

标签: react-native amazon-s3 react-native-fs

我已经通过aws控制台成功将带有预签名URL的图像上传到我的S3存储桶中,可以下载并显示它。这是使用简单JavaScript的代码:

const uploadUrl = 'https://myApp.s3.eu-central-1.amazonaws.com/myAppImages/3b2ab536....99&X-Amz-SignedHeaders=host'

const imageLocalPath= RNFS.DocumentDirectoryPath+'/images/3b2ab536-1256-49f5-a4bb-a42e213260f2.jpg'

const data = ({ uri: 'file://'+imageLocalPath, type: 'image/jpeg', name:  imageId +'.jpg',})


const futch = (url, opts, onProgress) => {
    return new Promise( (res, rej)=>{
        var xhr = new XMLHttpRequest();
        xhr.open(opts.method || 'PUT', url);
        xhr.setRequestHeader('Content-Type','image/jpeg');
        xhr.onload = e => res(e.target);
        xhr.onerror = rej;
        if (xhr.upload && onProgress)
            xhr.upload.onprogress = onProgress; // event.loaded / event.total * 100 ; //event.lengthComputable
        xhr.send(opts.body);
    });


    futch(uploadUrl, {
      method: 'PUT',
      body: data
    }, (e) => {
      const progress = e.loaded / e.total;
      this.setState((prevState) => {
        return { progress: prevState.progress}
      })
    }).then((res) => console.log('response from futch: ',res), (e) => console.log('error from futch: ',e))

当我尝试使用RNFS时,已上传图像,可以从S3控制台下载它,但无法显示它。

const uploadUrl = 'https://myApp.s3.eu-central-1.amazonaws.com/myAppImages/3b2ab536....99&X-Amz-SignedHeaders=host'

const imageLocalPath= RNFS.DocumentDirectoryPath+'/images/3b2ab536-1256-49f5-a4bb-a42e213260f2.jpg'


let fileToUpload = [{
      name: imageId +'.jpg',
      filename: imageId +'.jpg',
      filepath:  imageLocalPath,
      filetype: 'image/jpeg'
    }]

RNFS.uploadFiles({
      toUrl: uploadUrl,
      files: fileToUpload,
      headers: {
        "Content-Type": "multipart/form-data",
      },
      method: 'PUT',
      begin: this.setState({status:'uploadInitiated'}),
      progress:this.setState({status:'upload In Progress'}),
      }).promise.then((response) => {
        if (response.statusCode == 200){
           this.setState({status:'upload done!'})
        } else {
          console.log('SERVER ERROR');
        }
      })
      .catch((err) => {
        if(err.description === "cancelled") {
          // cancelled by user
        }
        console.log('error catched: ',err);
      });

好像RNFS发送的文件格式不正确,一定是我缺少了一些东西。

0 个答案:

没有答案