FormData in React Native

There are 2 things that I actually don’t know until read FormData implementation.

Image uploading

Yes, you can upload images! I’ve used react-native-file-upload until discovered how to use FormData in this case.

Using FormData in browser in very simple. For example, we have an input. So we need just append File object to FormData.

formData.append('username', 'Aleksei');
formData.append('userpic', myFileInput.files[0], 'doochik.jpg')

There is no File object or Blob in React Native. ImagePicker or CameraRoll gives us only file url, e.g., file://path/to/image.jpg.

The solution is to add special object with uri property as described in JSDoc

var photo = {
	uri: uriFromCameraRoll,
	type: 'image/jpeg',
	name: 'photo.jpg',
};

var body = new FormData();
body.append('photo', photo);
body.append('title', 'A beautiful photo!')

Field value must be string

I think this is actually the bug at this place.

Example

var fd = FormData();

fd.append('foo', 'bar'); // works
fd.append('image', {uri: 'file:///'}); // works

fd.append('number', 1); // EXCEPTION
fd.append('boolean', true); // EXCEPTION
comments powered by Disqus