简体   繁体   中英

How to send POST request with files in react-native android

I'm trying to send a file with rect-native 62.2 code with fetch request when i select the file my fill array is this ->

{"data": ~blob image data~,"fileName": "Screenshot_20200504_082033.jpg", "fileSize": 347275, "height": 1544, "isVertical": true, "originalRotation": 0, "path": "/storage/emulated/0/DCIM/Screenshots/Screenshot_20200504_082033.jpg", "timestamp": "2020-05-04T02:50:33Z", "type": "image/jpeg", "uri": "content://media/external/images/media/126441", "width": 720}

i'm using the library for selecting the data is react-native-image-picker

the fetch request i'm sending is will look like this

var picForm = new FormData();
          picForm.append('userId', userId);
          picForm.append('file', source) // <- this is the main data
fetch(API_HOST + 'user/profilePictureUpload', {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'multipart/form-data',
              Authorization: 'Basic jfjsfhsjkfhsjkjksksjjksfjkskfksdd',
              Authorizationkeyfortoken:''fjsfsfjsfsjhfsjkfhjksfjksfjsf,
            },
            body: picForm,
          }).then(res => res.text()).then(text => console.log(text)).catch(e => console.log(e));

for this code i'm getting an error source is [TypeError: Network request failed] when i try this

    var picForm = new FormData();
              picForm.append('userId', userId);
              picForm.append('file', {
  uri: source.uri, //<- content://media/external/images/media/126441
  type: 'image/jpeg',
  name: source.fileName //<- Screenshot_20200504_082033.jpg
})

for this code i'm getting an error source is [TypeError: Network request failed]

var picForm = new FormData();
          picForm.append('userId', userId);
          picForm.append('file', source.files[0]) // <- this is the main data

the error appear is undefined object

 var picForm = new FormData();
              picForm.append('userId', userId);
              picForm.append('file', 'files') // <- this is the main data

the network is correct but this is not i want to send this is the simple string do you guys any idea how to send the file with fetch request

please create image object like this way

 var imageData = {
 uri: iamge_path,
  type: file_type, //the mime type of the file
  name: file_name
}

const data = new FormData(); 
data.append("image",imageData)

Please make sure the request type is post, and your backend is handling the formdata correctly

This code working fine for me for multiple images upload, with photo description and user_id along with progress status

constructor() {
    super();
    this.state = {
      uploadPercentage: 0,
    }
  }

  // upload Files upload_Files = async () => {
  upload_File() {

    if (this.validate_Fields()) {
      const { image, images, files, description, userId, size } = this.state;
      console.log('AddPost Screen : upload_File:', 'userId:', userId, 'Files:', files, 'description:', description)
      // this.setState({ error: '', loading: true });

      if (this.state.type === 'image/jpeg') {

        console.log('AddPost Screen : upload_ files :', files);
        const formData = new FormData();
        formData.append('user_id', userId);
        formData.append('description', description);
        // formData.append('files[]', files);
        for (let i = 0; i < files.length; i++) {
          formData.append('files[]', {
            name: files[i].path.split('/').pop(),
            type: files[i].mime,
            uri: Platform.OS === 'android' ? files[i].path : files[i].path.replace('file://', ''),
          });
        }


        // upload percentage progress bar  ******************************************************
        const options = {
          onUploadProgress: (progressEvent) => {
            const { loaded, total } = progressEvent;
            let percent = Math.floor((loaded * 100) / total)
            console.log(`${loaded}kb of ${total}kb | ${percent}%`);

            if (percent < 100) {
              this.setState({ uploadPercentage: percent })
            }
          }
        }


        axios.post(API_URL + '/fileuploadapi/uploadPost', formData, options, {
          headers: { "Content-type": "multipart/form-data" }
        }).then((response) => {
          console.log(JSON.parse(JSON.stringify(response.status)));


          // upload percentage progress 
          this.setState({ uploadPercentage: 100 }, () => {
            setTimeout(() => {
              this.setState({ uploadPercentage: 0 })
            }, 1000);
          })


          this.cleanupImages();

          Alert.alert('Upload Post Successfully');
        }).catch((error) => {
          console.log(error);
          this.cleanupImages();

          Alert.alert('image Upload Post Failed  , Try again !');
        });

     }
   }
}



  // clear files data 
  cleanupImages() {

    this.setState({
      description: '',
      image: null,
      images: null,
      // video: '',
      files: '',
      uploadPercentage: 0,
    })
    ImagePicker.clean().then(() => {
      console.log('removed tmp images from tmp directory');
    }).catch(error => {
      alert(error);
    });
  }

If anything need let me know

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM