How to Upload Multiple Files React Native

Ariel Salem
2 min readSep 17, 2018

--

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,
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!

--

--

Ariel Salem

Full Stack Developer | Lover of Tech, Programming, and all things JavaScript