-
-
Save vedovato/a170e9e146fcd119b7d9710e177d06fd to your computer and use it in GitHub Desktop.
Upload a file to your server using react native / expo.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 | |
}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment