Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading a file in react native

How can I upload a file in react-native in the most easy way to the server? There is online too much information and libraries, thus I don't know if they're safe to use.

Thank you.

like image 288
oron cohen Avatar asked Jul 23 '18 20:07

oron cohen


People also ask

How do I upload a file to react?

In order to upload files, the 'content-type' header must be set to 'multipart/form-data'. new FormData() creates a new empty formData object that we send as the payload in our POST request. Our POST request assumes there is an API endpoint on our backend server at http://localhost:3000/uploadFile. We're done!

How do I upload an image into react native?

To handle image uploads we need to set the encoding type to multipart/form-data which means we need to format our data differently. Thus the createFormData function. This function will go ahead and take the image we selected and add it to the photo field of the form data with the required info.


2 Answers

This is the method to upload file to server using fetch

        const body = new FormData();

        //String Key value pair appending to body   
        body.append('KEY', VALUE);
        body.append('KEY', VALUE);
        body.append('KEY', VALUE);

        //Appending file to body
        body.append(KEY_AS REQUIRED_IN_SERVICE, {
                uri: PASS_URI_OF_THE_FILE,
                type: 'image/jpeg', //This is the file type .. you can define according to your requirement
                name: 'photo.jpg',   //File name you want to pass
            })
        //Service call                        
        fetch(YOUR_URL, {
            method: 'POST',
            headers: new Headers({
                YOUR_HEADER_PARAMS
            }),
            body: body
        })
            .then(res => res.json())
            .then((responseJson) => {

               //GET RESPONSE SUCCESS OF FAILURE

            })
            .catch((error) => {
               //ERROR 
            });
    }
like image 112
Jay Thummar Avatar answered Oct 21 '22 00:10

Jay Thummar


give a try https://github.com/itinance/react-native-fs

we use in production in some apps

like image 23
dvvtms Avatar answered Oct 21 '22 01:10

dvvtms