oron cohen
oron cohen

Reputation: 85

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.

Upvotes: 5

Views: 4261

Answers (2)

Jay Thummar
Jay Thummar

Reputation: 2299

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 
            });
    }

Upvotes: 5

dvvtms
dvvtms

Reputation: 627

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

we use in production in some apps

Upvotes: 3

Related Questions