3

I am using react-native-document-picker and rn-fetch-blob to upload the file. It's working as expected for a single file. But I couldn't able to upload multiple files to the server.

Upload function

const uploadPic=()=>{
    // alert('ddf');
  
    RNFetchBlob.fetch('POST', 'http://localhost/test.upload.php', {
      Authorization : "Bearer access-token",
      otherHeader : "foo",
      'Content-Type' : 'multipart/form-data',
    }, [
      // element with property `filename` will be transformed into `file` in form data
      {name : 'image', filename : singleFile.name, type: singleFile.type, data: RNFetchBlob.wrap(singleFile.uri)}
    ]).then((resp) => {
      console.log(resp);
      
      alert('your image uploaded successfully');
     
    })
  } 

It's working fine to upload the single file but I need to upload multiple docs.

Select Function

let selectFile = async () => {
    //Opening Document Picker to select one file
    try {
      const res = await DocumentPicker.pick({
        //Provide which type of file you want user to pick
        type: [DocumentPicker.types.allFiles],
        //There can me more options as well
        // DocumentPicker.types.allFiles
        // DocumentPicker.types.images
        // DocumentPicker.types.plainText
        // DocumentPicker.types.audio
        // DocumentPicker.types.pdf
      });
      //Printing the log related to the file
      console.log('res : ' + JSON.stringify(res));
      //Setting the state to show single file attributes
      setSingleFile(res);
    } catch (err) {
      setSingleFile(null);
      //Handling any exception (If any)
      if (DocumentPicker.isCancel(err)) {
        //If user canceled the document selection
        alert('Canceled from single doc picker');
      } else {
        //For Unknown Error
        alert('Unknown Error: ' + JSON.stringify(err));
        throw err;
      }
    }
  };

I changed this line from const res = await DocumentPicker.pick({ to const res = await DocumentPicker.pickMultiple({

In the console, the array of all the files are posted.

Now I need to upload all the files to the server, Looking for a solution to loop all the data in RNFetchBlob.fetch.

I have added the loop in the function as below

const uploadPic=()=>{
    // alert('ddf');
  
    RNFetchBlob.fetch('POST', 'http://localhost/test.upload.php', {
      Authorization : "Bearer access-token",
      otherHeader : "foo",
      'Content-Type' : 'multipart/form-data',
    }, [ singleFile.map((item, key) => (
      {name : 'image[]', filename : item.name, type: item.type, data: RNFetchBlob.wrap(item.uri)}
    ))
      // element with property `filename` will be transformed into `file` in form data
      
    ]).then((resp) => {
      console.log(resp);
      
      alert('Document uploaded successfully');
     
    })
  } 

In the console the error which i am getting now

RNFetchBlob failed to create request multipart body :com.facebook.react.bridge.ReadableNativeArray cannot be cast to com.facebook.react.bridge.ReadableNativeMap
[Tue Jun 23 2020 05:36:26.918]  WARN     Attempt to invoke virtual method 'int java.io.InputStream.read(byte[], int, int)' on a null object reference
[Tue Jun 23 2020 05:36:27.363]  LOG      {"array": [Function anonymous], "base64": [Function anonymous], "blob": [Function anonymous], "data": "{\"Message\":\"sorry\",\"Status\":\"Error\"}",
user2468312
  • 361
  • 2
  • 7
  • 21

1 Answers1

0

Came ages after, but maybe helps someone else. Faced the same issue, and I could make it work wrapping the array of files in a for loop before sending it to RNFetchBlob.fetch. I was using react-native-document-picker to get the files.

 const [multipleFiles, setMultipleFiles] = useState([]);

 let data = []
    for(let i = 0; i < multipleFiles.length; i++){
        data.push(
            { name : 'submit', data: 'ok' },
            { name : 'files', filename : multipleFiles[i].name, data: RNFetchBlob.wrap(multipleFiles[i].uri) },
        )
    }

Then on the request ...

RNFetchBlob.fetch('post', 'http://myendpoint.com/api/example' , {
         Authorization : "Bearer access-token",
        'Content-Type' : 'multipart/form-data',

      }, data).then((res) => {
        console.log(res)
      })

Hope it helps, it did for me! ;D

Juliet
  • 25
  • 7