【问题标题】:React-Native multipart photo upload not working in androidReact-Native 多部分照片上传在 android 中不起作用
【发布时间】:2019-07-18 11:40:56
【问题描述】:

我正在尝试使用 react-native 中的 fetch multipart upload 将图像文件发送/上传到我的后端服务,但是 fetch multipart form data upload 不适用于 android,但是我尝试了不同的示例。

图片上传多部分表单数据 API 基于 php,适用于 iOS react-native 应用。

我正在使用 react-native-photo-upload 库来拍照。

storePicture(PicturePath:string) {
console.warn(PicturePath);
if (PicturePath) {
  const apiUrl = `${Constants.APIHOST}updateprofileimage.php`;
  // Create the form data object
  var data = new FormData();
  data.append('profileimage', { uri:PicturePath, name: 'profileimage.jpg', type: 'image/jpg/jpeg' });
  data.append('accesstoken', this.state.user.sAccessToken);
  data.append('react-native', 1);

  // Create the config object for the POST // You typically have an OAuth2 token that you use for authentication
  const config = { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'multipart/form-data;' }, body: data };
  fetch(apiUrl, config)
  .then(responseData => { // Log the response form the server
    // Here we get what we sent to Postman back
    console.warn(`response:${responseData}`);
  })
  .catch(err => {
    console.warn(err);
  });
}}

这是我如何调用 storePicture() 函数的示例。

<PhotoUpload onResizedImageUri={
        avatar => {
          if (avatar) {
            this.storePicture(avatar.path);
          }
        }}
      >
        <Image source={{uri: this.state.user.sProfileImageUrl}} style={{resizeMode:"cover", marginTop:8.0, backgroundColor:'transparent', height:120.0, width:120, borderRadius:60.0, borderWidth:0.0, borderColor:'transparent'}}/>
      </PhotoUpload>

【问题讨论】:

    标签: android react-native fetch multipartform-data


    【解决方案1】:
    uploadProfileImage = async (image:var) => {
    this.setState({
      loading: true
    });
    var RNFS = require('react-native-fs');
    const path = Style.IS_IOS ? image.uri : image.path;
    var fileName = path.split('/').pop();
    var fileType = fileName.split('.').pop();
    var filePath = Style.IS_IOS ? path : 'file://' + path;
    
    const apiURL = `${Constants.APIHOST}updateprofileimage.php`;
    const formData = new FormData();
    formData.append('accesstoken', this.state.user.sAccessToken);
    formData.append('reactnative', 1);
    formData.append('profileimage', {
      uri:filePath,
      name: fileName,
      type: `image/${fileType}`,
    });
    try {
      const response = await fetch(apiURL, {
        body: formData,
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data',
          'Accept': 'application/json',
        },
      })
      const json = await response.json()
      this.handleUploadImageResponse(json);
    } catch (err) {
      this.setState({
        loading: false
      },console.log('catch Error: '+ err));
    }
    

    }

    我正在回答我自己的问题,因为我还没有为其他面临同样问题的用户找到任何有效的答案。

    如果我可以改进我的答案/帖子,或者如果需要我的任何帮助,请告诉我。

    【讨论】:

      【解决方案2】:

      通过 Multipart FormData 将图像上传到 API

      uploadPicture = () => {
        console.log(
          "Image Upload urI = " + JSON.stringify(this.state.imageSourceUri.uri)
        );
        this.setState({ loading: true });
      
        const form = new FormData();
        form.append("fileToUpload", {
          uri: this.state.imageSourceUri.uri,
          type: "image/jpg",
          name: "12334"
        });
        fetch("http://119.82.97.221/HPBSProjectApi2/api/HPBS/PostFormData", {
          method: "post",
          body: form
        })
          .then(response => response.json())
          .then(response => {
            console.log("response = " + response);
            this.setState({
              loading: false
            });
          });
      };
      

      【讨论】:

        猜你喜欢
        • 2022-09-29
        • 2021-10-17
        • 1970-01-01
        • 2021-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        相关资源
        最近更新 更多