React-native-fetch-blob: Error in uploading multiple images! how to upload multiple images?

Created on 8 Jan 2017  路  8Comments  路  Source: wkh237/react-native-fetch-blob

I was creating a upload form which sends multiple images to API. But i'm getting error whenever i'm attaching more than 1 image.
Single file upload with data is working but multiple files with data are not working.

Here is the piece of code:

RNFetchBlob.fetch('POST', 'https://www.test.test/api/v1/test.php', {
      'Content-Type' : 'multipart/form-data',
    }, [
      { name : 'image1', data: this.state.uploadFiles[0].uri},
      { name : 'image2', data: this.state.uploadFiles[1].uri},
      { name : 'image3', data: this.state.uploadFiles[2].uri},
      { name : 'image4', data: this.state.uploadFiles[3].uri},
      { name : 'image5', data: this.state.uploadFiles[4].uri},
      { name : 'image1_content', data: String(this.state.imageContent1)},
      { name : 'image2_content', data: String(this.state.imageContent2)},
      { name : 'image3_content', data: String(this.state.imageContent3)},
      { name : 'image4_content', data: String(this.state.imageContent4)},
      { name : 'image5_content', data: String(this.state.imageContent5)},
      { name : 'id', data: String(this.state.id)},
      { name : 'main_content', data: String(this.state.content)}
    ]).uploadProgress((written, total) => {
        console.log('uploaded', written / total);

    })
    .then((resp) => resp.json())
    .then((responseJson) => {
      console.log(responseJson);
    })
    .catch((err) => {
      console.log(err);
    })

I always get this error whenever i upload multiple files:

SyntaxError: Unexpected token < in JSON at position 0

needs feedback

Most helpful comment

FYI, if you need to post files as array in PHP, you need to specify your arguments as follows:

[
  { name: 'image[]', filename: '...', data: '...' },
  { name: 'image[]', filename: '...', data: '...' },
  // ...
]

In PHP, you'll receive and get something like this:

$files = $_FILES['image'];
$filename1 = $files['name'][0];
$filename2 = $files['name'][1]; // $tmp2 = $files['tmp_name'][1];
// ... so on
// ... or better use foreach

This is how we process $_FILES when uploading multiple files in the browser so might be more compatible if we send/accept the same way.

Hope this helps someone somehow 馃槃

All 8 comments

@mdmush , does it happen on both Android and IOS ? From the code snippet I suppose the image content are encoded into BASE64 string ? If you're going to upload files using their URI, you'll need filename and also use RNFetchBlob.wrap to wrap the URI.

Actually i was testing on Android device for now. And yeah, it is BASE64 string.
Thanks for the solution. I've added filename and wrapped the URI with RNFetchBlob.wrap.
Everything works fine on my end, but now the problem is i'm not getting any data in API. The data remains null. So tell me what to do?

Now the code looks like this:

RNFetchBlob.fetch('POST', 'https://www.test.test/api/v1/test.php', { 'Content-Type' : 'multipart/form-data', }, [ { name : 'image1', filename : 'image1.jpg', data: RNFetchBlob.wrap(this.state.uploadFiles[0].uri)}, { name : 'image2', filename : 'image2.jpg', data: RNFetchBlob.wrap(this.state.uploadFiles[1].uri)}, { name : 'image3', filename : 'image3.jpg', data: RNFetchBlob.wrap(this.state.uploadFiles[2].uri)}, { name : 'image4', filename : 'image4.jpg', data: RNFetchBlob.wrap(this.state.uploadFiles[3].uri)}, { name : 'image5', filename : 'image5.jpg', data: RNFetchBlob.wrap(this.state.uploadFiles[4].uri)}, { name : 'image1_content', data: String(this.state.imageContent1)}, { name : 'image2_content', data: String(this.state.imageContent2)}, { name : 'image3_content', data: String(this.state.imageContent3)}, { name : 'image4_content', data: String(this.state.imageContent4)}, { name : 'image5_content', data: String(this.state.imageContent5)}, { name : 'main_content', data: String(this.state.content)} ]).uploadProgress((written, total) => { console.log('uploaded', written / total); }) .then((resp) => resp.json()) .then((responseJson) => { console.log(responseJson); }) .catch((err) => { console.log(err); })

@mdmush , thanks for the information. I have just test your code with in my end. I and it works fine. Could you provide raw request body from server ? It'd be helpful.

Okkay.

here is my server code:

<? define('UPLOAD_DIR', 'content/'); $final= array(); $img1 = $_REQUEST['image1']; $img2 = $_REQUEST['image2']; $img3 = $_REQUEST['image3']; $img4 = $_REQUEST['image4']; $img5 = $_REQUEST['image5']; $final["img1"] = $img1; $final["img2"] = $img2; $final["img3"] = $img3; $final["img4"] = $img4; $final["img5"] = $img5; echo(json_encode($final)); ?>

Right now, i'm just checking if the data is reaching to the API or not. If this is wrong, please send me the code you tested.

there?

FYI, if you need to post files as array in PHP, you need to specify your arguments as follows:

[
  { name: 'image[]', filename: '...', data: '...' },
  { name: 'image[]', filename: '...', data: '...' },
  // ...
]

In PHP, you'll receive and get something like this:

$files = $_FILES['image'];
$filename1 = $files['name'][0];
$filename2 = $files['name'][1]; // $tmp2 = $files['tmp_name'][1];
// ... so on
// ... or better use foreach

This is how we process $_FILES when uploading multiple files in the browser so might be more compatible if we send/accept the same way.

Hope this helps someone somehow 馃槃

My question is same but my images are dynamic like if user select 1 image then only one image has to be post in API and so on. I am creating array in state for Images. any dynamic solution for this ???

here is my code.

ImagePicker.showImagePicker(options, (response) => {
                console.log('Response = ', response);

                if (response.didCancel) {
                    console.log('User cancelled image picker');
                }
                else if (response.error) {
                    console.log('ImagePicker Error: ', response.error);
                }
                else if (response.customButton) {
                    console.log('User tapped custom button: ', response.customButton);
                }
                else {
                    let source = { uri: response.uri };
                    setTimeout(() => {
                        this.setState({
                            Images: [...this.state.Images, response.data]
                        }); // set images array in state I want to push that array in API
                    }, 300);
                }
            });

I finally find a way to do it 馃挴
here is the code may it help someone somehow 馃槃

RNFetchBlob.fetch('POST', '***ur-url***', {
                        'Content-Type': 'multipart/form-data',
                    }, [
                            { name: 'image[]', filename: 'image1.png', type: 'image/png', data: this.state.Images[0] },
                            { name: 'image[]', filename: 'image2.png', type: 'image/png', data: this.state.Images[1] },
                            { name: 'image[]', filename: 'image3.png', type: 'image/png', data: this.state.Images[2] },
                            {
                                name: 'formData', data: JSON.stringify([{
                                    "plant": selectedPlant,
                                    "description": description,
                                    "user_id": userID,
                                    "plant_id": selectedPlantID,
                                    "method": "submitData"
                                }])
                            }
                        ]).then((response) => response.json())
                        .then((responseData) => {

                            if (responseData.status) {
                                this.showAlert('Success', 'Data Submitted Successfully');
                                setTimeout(() => {
                                    this.setState({
                                        description: '',
                                        selectedPlant: '',
                                        Images: [],
                                        loadCat: false
                                    })
                                }, 300);
                            } else {
                                this.showAlert('Error', responseData.message);
                            }
                            // ...
                        }).catch((err) => {
                            // ...
                        })
Was this page helpful?
0 / 5 - 0 ratings

Related issues

sivakumar-cf picture sivakumar-cf  路  4Comments

mykelaballe picture mykelaballe  路  4Comments

fbacker picture fbacker  路  4Comments

timsuchanek picture timsuchanek  路  4Comments

aouaki picture aouaki  路  3Comments