Home > Enterprise >  How to append array of images to server using formdata react native?
How to append array of images to server using formdata react native?

Time:11-19

I’m trying to post an item to my server. I’m using React Native for my front end and Laravel as my back-end. I have tried it many times but it keeps giving me Network request failed. Though I am trying it on postman and it works fine.

this is my demo code:

var dummyArray = [
                { 
                type: "image/jpeg", 
                uri: "file:///storage/emulated/0/Android/data/com..../files/Pictures/4cbc8fa0-5978-42a6-89ab-ea9639cb43e4.jpg", 
                name: ("file:///storage/emulated/0/Android/data/com.../files/Pictures/4cbc8fa0-5978-42a6-89ab-ea9639cb43e4.jpg").split("/").pop() 
                },
                { 
                    type: "image/jpeg", 
                    uri: "file:///storage/emulated/0/Android/data/com..../files/Pictures/e3de766a-5c67-4926-9a56-93b0c989970a.jpg", 
                    name: ("file:///storage/emulated/0/Android/data/com..../files/Pictures/e3de766a-5c67-4926-9a56-93b0c989970a.jpg").split("/").pop() 
                }
            ]

 const formdata = new FormData();
 formdata.append('images[]', this.state.imageArray);

CodePudding user response:

You are passing whole array as a single param which is wrong. You should add all the images one by one in form data

 let formData = new FormData();
        if (images.length > 0) {
          images.forEach((element) => {
            formData.append('images', element);
          });
        } else {
          formData.append('images', undefined);
        }

CodePudding user response:

i have resolved my query with following code:

    Object.keys(dummyArray).forEach((item, i) => {
                                    
 formdata.append(`images[${item}]`, 
     {
          uri: dummyArray[item].uri,
          name: dummyArray[item].name,
          type: dummyArray[item].type
    }
 );
})

CodePudding user response:

I have resolve similar and like below:

submitImage(images = [{ uri: "", fileName: "", type: "" }]) {
    const oFormData = new FormData();
    images.map((val) => {
        oFormData.append("image", {
            uri: val.uri,
            type: val.type,
            name: val.fileName
        });
    });
    return axios.post(PostServiceUrl, oFormData);
}
  • Related