通过使用 aws-sdk 在 s3 Bucket 上上传图像来反应原生

Sub*_*tel 2 javascript amazon-s3 amazon-web-services reactjs react-native

我正在使用aws-sdks3 存储桶上的上传图像。请看下面我的代码,我已经在里面度过了一天。

uploadImageOnS3 = () => {

    var S3 = require("aws-sdk/clients/s3");

    const BUCKET_NAME = "testtest";
    const IAM_USER_KEY = "XXXXXXXXXXXXX";
    const IAM_USER_SECRET = "XXXXX/XXXXXXXXXXXXXXXXXXXXXX";

    const s3bucket = new S3({
      accessKeyId: IAM_USER_KEY,
      secretAccessKey: IAM_USER_SECRET,
      Bucket: BUCKET_NAME
    });
    let contentType = "image/jpeg";
    let contentDeposition = 'inline;filename="' + this.state.s3BucketObj + '"';
         let file= {
         uri: this.state.fileObj.uri,
         type: this.state.fileObj.type,
         name: this.state.fileObj.fileName

     };
    s3bucket.createBucket(() => {
      const params = {
        Bucket: BUCKET_NAME,
        Key: this.state.s3BucketObj,
        Body: file,
        ContentDisposition: contentDeposition,
        ContentType: contentType

      };
      s3bucket.upload(params, (err, data) => {
        if (err) {
          console.log("error in callback");
          console.log(err);
        }
        // console.log('success');
        console.log(data);

      });
    });
  };
Run Code Online (Sandbox Code Playgroud)

错误:

不受支持的正文有效负载对象

请帮我缩短我也react-native-image-picker用于图片上传。

Van*_*hta 8

您必须在主体流中使用数组缓冲区来传递数据对象。根据 aws 文档,您可以在 body 参数中传递数据流、字符串、数组缓冲区或 blob 数据类型。

请检查以下代码,这将解决您的问题,

import fs from "react-native-fs";
import { decode } from "base64-arraybuffer";

uploadImageOnS3 = async() => {

    var S3 = require("aws-sdk/clients/s3");

    const BUCKET_NAME = "testtest";
    const IAM_USER_KEY = "XXXXXXXXXXXXX";
    const IAM_USER_SECRET = "XXXXX/XXXXXXXXXXXXXXXXXXXXXX";

    const s3bucket = new S3({
      accessKeyId: IAM_USER_KEY,
      secretAccessKey: IAM_USER_SECRET,
      Bucket: BUCKET_NAME,
      signatureVersion: "v4"
    });
    let contentType = "image/jpeg";
    let contentDeposition = 'inline;filename="' + this.state.s3BucketObj + '"';
    const fPath = this.state.fileObj.uri;

    const base64 = await fs.readFile(fPath, "base64");
    //console.log(base64);

    const arrayBuffer = decode(base64);
    //console.log(arrayBuffer);
    s3bucket.createBucket(() => {
      const params = {
        Bucket: BUCKET_NAME,
        Key: this.state.s3BucketObj,
        Body: arrayBuffer,
        ContentDisposition: contentDeposition,
        ContentType: contentType

      };
      s3bucket.upload(params, (err, data) => {
        if (err) {
          console.log("error in callback");
          console.log(err);
        }
        // console.log('success');
        console.log(data);

      });
    });
  };
Run Code Online (Sandbox Code Playgroud)