React-native上传图片到amazons s3

Mic*_*cki 6 javascript file-upload amazon-s3 fetch react-native

我想将我的应用程序中的图像上传到S3服务器.我已经计算了所有数据和代码(在计算机上使用curl测试),但我无法弄清楚如何正确调用'fetch'.我得到回应:

'您指定的至少一个前提条件不成立.条件:Bucket POST必须是enclosure-type-multipart/form-data'

如何在react-natives fetch中重新创建表单数据?没有我可以附加的FormData,然后像在fetches示例中一样发送它.

编辑:谢谢@ philipp-von-weitershausen,请注意您已添加此功能.但是我有一些麻烦叫它.我得到"不支持的BodyInit类型".发现那是因为在fetch.js中:"support.formData"返回false.我打电话给fetch时我错过了什么?

我的代码示例:

 var form = new FormData();
 form.append("FormData", true)
 form.append("name", this.state.invoiceNumber)
 form.append("key", this.state.invoiceNumber)
 form.append("Content-Type", "image/png")
 form.append('file', this.props.uri)
 //alert(FormData.prototype.isPrototypeOf(form))

  fetch(amazon_url,{body: form,mode: "FormData", method: "post", headers: {"Content-Type": "multipart/FormData"}})
          .then((response) => response.json())
          .catch((error) => {
             alert("ERROR " + error)
          })
          .then((responseData) => {
             alert("Succes "+ responseData)
          })
          .done();
Run Code Online (Sandbox Code Playgroud)

Mic*_*cki 7

有人问,所以我发布了我是如何做到的.它很久以前就已经安静了所以如果你有任何评论或者其他事情真的很糟糕我会对评论家开放;)照片是从cameraRoll读取并存储在'latestPhoto'中.

将照片上传到S3服务器:

第1步:生成数据:

_addTextParam() {
    var textParams = this.state.textParams;
    s3_upload_id = this.makeid()
    textParams.push({ name: "key", value: this.state.upload_path + s3_upload_id + '/' + this.state.att_name + ".jpg" })
    textParams.push({ name: "AWSAccessKeyId", value: this.state.key })
    textParams.push({ name: "acl", value: "public-read" })
    textParams.push({ name: "success_action_status", value: "201" })
    textParams.push({ name: "policy", value: this.state.policy })
    textParams.push({ name: "signature", value: this.state.signature })
    textParams.push({ name: "Content-Type", value: "image/jpeg" })

    this.setState({ textParams: textParams });
  }
Run Code Online (Sandbox Code Playgroud)

第2步:发送数据:

  _send() {

    this._addTextParam()
    var xhr = new XMLHttpRequest();
    xhr.open('POST', "http://" + this.state.fs_domain + "." + this.state.server);
    xhr.onload = () => {
      this.setState({ isUploading: false });
      if (xhr.status !== 201) {
        AlertIOS.alert( 
          'Upload failed',
          'Expected HTTP 200 OK response, got ' + xhr.status + "/" + xhr.responseText
        );
        return;
      }

      if (!xhr.responseText) {
        AlertIOS.alert(
          'Upload failed',
          'No response payload.'
        );
        return;
      }
      var index = xhr.responseText.indexOf( "http://" + this.state.fs_domain + "." + this.state.server);
      if (index === -1) {
        AlertIOS.alert(
          'Upload failed',
          'Invalid response payload.'
        );
        return;
      }
      var url = xhr.responseText.slice(index).split('\n')[0];
      this.state.s3_file_id = xhr.responseText.split('Tag>"')[1].split('"')[0]
      this.state.s3_file_path = xhr.responseText.split('Location>')[1].split('<')[0]
      this.setState({ isUploading: false });
      RCTDeviceEventEmitter.emit('Uploaded')

    };
    var formdata = new FormData();

    this.state.textParams.forEach((param) => {
        formdata.append(param.name, param.value)
      }
    );

    formdata.append('file', {...this.state.latestPhoto, name: (this.state.att_name+".jpg") });

    xhr.send(formdata);
    this.setState({ isUploading: true });

  },
Run Code Online (Sandbox Code Playgroud)


Pir*_*hah 6

@MichałZubrzycki谢谢你,上传图片的代码对我有用,几乎没有变化.

const photo = {
  uri: user.profilePicture,
  type: "image/jpeg",
  name: "photo.jpg"
};
const form = new FormData();
form.append("ProfilePicture", photo);
fetch(Constants.API_USER + "me/profilePicture", {
  body: form,
  method: "PUT",
  headers: {
    "Content-Type": "multipart/form-data",
    Authorization: "Bearer " + user.token
  }
})
  .then(response => response.json())
  .catch(error => {
    console.log("ERROR ", error);
  })
  .then(responseData => {
    console.log("Success", responseData);
  })
  .done();
Run Code Online (Sandbox Code Playgroud)


Phi*_*sen 5

multipart/form-dataFormData对混合有效载荷(JS字符串+图像有效载荷)的React Native(通过XHR API)的支持正在进行中.它应该很快登陆GitHub.

  • aaaand它登陆:https://github.com/facebook/react-native/commit/f4bf80f3ea3b7ed6aee8b068ec1a289e0965eb5e (2认同)