How To Upload Multiple Files React Native - by Ariel Salem - Medium

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

10/31/21, 6:02 PM How to Upload Multiple Files React Native | by Ariel Salem | Medium

Get started Open in app

Ariel Salem
92 Followers About Follow

How to Upload Multiple Files React Native


Ariel Salem Sep 17, 2018 · 2 min read

After spending the better part of week wrestling with React-Native packages and native
JavaScript implementations to allow users to upload photos from their phone to the
database in bundles, I finally found a simple native solution that’s quick and easy to use.
This solution was derived via a trial and error process that I hope no one else will have to
go through.

Setup A Form:
Our first step in uploading our files as a bundle would be to create a FormData object.

let data = new FormData();

This will allow us to append & send our data as a multipart/form-data.

Fill Form Out:


The next thing we have to do is append the data we want to send onto our form. This
effectively allows us to bundle our information into an easily transmittable multipart
object:

this.state.selectedImages.forEach((item, i) => {

data.append("doc[]", {

uri: item.uri,

https://medium.com/@ariel.salem1989/how-to-upload-multiple-files-react-native-e9577a5de106 1/3
10/31/21, 6:02 PM How to Upload Multiple Files React Native | by Ariel Salem | Medium

type: "image/jpeg",

name: item.filename || `filename${i}.jpg`,

});

});

Once we’ve finished appending the relevant data onto our FormData, we can go ahead
and submit our data using JavaScript’s native fetch method.

Submit Data:
Fortunately for us, JavaScript’s fetch method allows us to send multipart/form-data as
easily as you would any other data.

fetch(`${config.apiBase}/load/${this.props.id}/uploadconfirmation`, {

method: "post",

headers: {

Accept: "application/x-www-form-urlencoded",

Authorization: `Bearer ${this.props.user.token}`,

},

body: data,

}).then(res => res.json())

.then(res => {

Alert.alert(

"Success",

"Bill of Loading Uploaded Successfully!",

[{ text: "OK", onPress: () => that.props.close() }],

{ cancelable: false }

);

})

.catch(err => {

console.error("error uploading images: ", err);

});

There you have it! If that helped you avoid a headache, feel free to applaud this post!

JavaScript React Native React Photos Image

https://medium.com/@ariel.salem1989/how-to-upload-multiple-files-react-native-e9577a5de106 2/3
10/31/21, 6:02 PM How to Upload Multiple Files React Native | by Ariel Salem | Medium

About Write Help Legal

Get the Medium app

https://medium.com/@ariel.salem1989/how-to-upload-multiple-files-react-native-e9577a5de106 3/3

You might also like