React-Native将jpg文件上传到s3

时间:2018-06-21 01:04:37

标签: react-native

我一直试图将文件上传到S3-要求是该文件是从Android还是iOS上都能被网络读取的(即是普通的jpeg文件)。

我尝试使用react-native-fetch-blob和Service失败 但我只能上传的是该文件的baset64表示形式。

这是不可接受的,因为无法通过Web界面本地读取。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

使用aws3 lib的步骤。

  1. 使用命令npm install --save react-native-aws3

  2. 安装aws3 react-native库
  3. 使用以下代码作为模板上传jpg。

    import { RNS3 } from 'react-native-aws3';
    
    // No need to convert to Base 64. You can directly upload the image.
    const imageFile = {
      uri: `file://${image.path}`,
     name: "image.png",
     type: "image/png"
    }
    
    // Replace your s3 configuration here. Also move this to separate file for better use.
    const options = {
      keyPrefix: "uploads/",
      bucket: "your-bucket",
      region: "us-east-1",
      accessKey: "your-access-key",
      secretKey: "your-secret-key",
      successActionStatus: 201
    }
    
    RNS3.put(imageFile, options).then(response => {
      if (response.status !== 201) throw new Error("Failed to upload image to S3");
    
      console.log(response.body);
      /**
      * {
      *   postResponse: {
      *     bucket: "your-bucket",
      *     etag : "9f620878e06d28774406017480a59fd4",
      *     key: "uploads/image.png",
      *     location: "https://your-bucket.s3.amazonaws.com/uploads%2Fimage.png"
      *   }
      * }
      */
    });
    

还有一个本地库,用于响应本地调用react-native-s3。如果您也想查看一下。

答案 1 :(得分:0)

此功能对我有用,希望有帮助

async function uploadFile(signed_url, uri, fileName, fileType, callback) {
    const xhr = new XMLHttpRequest();
    xhr.open('PUT', signed_url);
    xhr.setRequestHeader('Content-Type', fileType);
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                console.log(log_sign, "upload success");
                callback(xhr.status)
            }
        }
    };
    xhr.send({uri: uri, type: fileType, name: fileName})
};