Skip to content

Instantly share code, notes, and snippets.

@Tamal
Last active March 28, 2024 13:53
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save Tamal/9231005f0c62e1a3f23f60dc2f46ae35 to your computer and use it in GitHub Desktop.
Save Tamal/9231005f0c62e1a3f23f60dc2f46ae35 to your computer and use it in GitHub Desktop.
React Native File upload using XMLHttpRequest
_uploadSnap() {
var url = 'http://example.com/upload'; // File upload web service path
var photo = {
uri: this.state.picturePath, // CameralRoll Url
type: 'image/jpeg',
name: 'photo.jpg',
};
var formData = new FormData();
formData.append("file", photo);
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
console.log('OPENED', xhr.status);
xhr.onprogress = function () {
console.log('LOADING', xhr.status);
};
xhr.onload = function () {
console.log('DONE', xhr.status);
};
xhr.setRequestHeader('authorization', this.state.token);
xhr.send(formData);
}
@navyjax2
Copy link

navyjax2 commented Apr 6, 2018

For those without something that recognizes what that "authorization" header means, it would need to be xhr.setRequestHeader('application/json;charset=UTF-8'); instead. It's also be worth mentioning that this set up should NOT use FormData, but should just do xhr.send(JSON.stringify(photo)); and leave out var formData altogether if you're going to post to an MVC method, because it doesn't like multipart/form-data content, I've noticed, and that's the header that would need to be set if using FormData. Just post as JSON and use an MVC model on the back-end, so your post method would look like [System.Web.Http.HttpPost] public virtual ActionResult Post([FromBody]MyModel myModelObject) { ... } and your model is public MyModel { public string uri { get; set; } public string type { get; set; } public string name { get; set; } } Also worth noting that this example does NOT actually send the photo, itself, just the URL to it. Even the FormData object was basically just a re-casting of var photo, and nothing to do with posting a file, making it unnecessary.

For anyone finding this via Google, like I did, if you want to post the actual file, it's best to convert it to a base64 byte string first, then send it along in a JSON object, like var photo up there is - just add another thing for file: myFileString, where myFileString is the file contents. I have an example of how to get those contents using a React DropZone here: https://stackoverflow.com/questions/32556664/getting-byte-array-through-input-type-file/49660172#49660172 and a working example of changing the input.files[0] to an array here: https://stackoverflow.com/questions/37134433/convert-input-file-to-byte-array/49676679#49676679

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