Skip to content

Instantly share code, notes, and snippets.

@nandorojo
Created May 2, 2019 23:30
Show Gist options
  • Save nandorojo/c641c176a053a9ab43462c6da1553a1b to your computer and use it in GitHub Desktop.
Save nandorojo/c641c176a053a9ab43462c6da1553a1b to your computer and use it in GitHub Desktop.
Upload a file to your server using react native / expo.
/*
IF YOU WANT TO UPLOAD ONE FILE, USE THE CODE BELOW.
SEE THE BOTTOM OF THE GIST TO SEE HOW TO UPLOAD MULTIPLE FILES.
HERE'S AN EXAMPLE SOMEONE MADE USING CLOUDINARY: https://gist.github.com/jamielob/5c1a5dc84e50e4507b71299d993dffec
*/
// 1. initialize request
const xhr = new XMLHttpRequest();
// 2. open request
xhr.open('POST', uploadUrl);
// 3. set up callback for request
xhr.onload = () => {
const response = JSON.parse(xhr.response);
console.log(response);
// ... do something with the successful response
};
// 4. catch for request error
xhr.onerror = e => {
console.log(e, 'upload failed');
};
// 4. catch for request timeout
xhr.ontimeout = e => {
console.log(e, 'upload timeout');
};
// 4. create formData to upload
const formData = new FormData();
formData.append('file', {
uri: 'some-file-path', // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
type: `${type}/${fileEnding}`, // example: image/jpg
name: `upload.${fileEnding}` // example: upload.jpg
});
// 6. upload the request
xhr.send(formData);
// 7. track upload progress
if (xhr.upload) {
// track the upload progress
xhr.upload.onprogress = ({ total, loaded }) => {
const uploadProgress = (loaded / total);
console.log(uploadProgress);
};
}
// REPLACE #4 WITH THE CODE BELOW IF YOU'RE UPLOADING AN ARRAY OF MULTIPLE FILES
// 4. create formData to upload
const arrayOfFilesToUpload = [
// ...
];
const formData = new FormData();
arrayOfFilesToUpload.forEach(file => {
formData.append('file', {
uri: file.uri, // this is the path to your file. see Expo ImagePicker or React Native ImagePicker
type: `${type}/${fileEnding}`, // example: image/jpg
name: `upload.${fileEnding}` // example: upload.jpg
});
})
@stharvey
Copy link

stharvey commented Nov 30, 2022

Hello again, I've figured this out. Just in case this helps someone else:

The issue was occurring when running a development bundle on a metro server - axios/xhr was reporting on the status of the upload of the file to the metro proxy rather than to it's final destination on the net.

When I created an apk build everything worked correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment