Uploading image to Node from React Native

Rohith R
Zero Equals False
Published in
3 min readJan 8, 2018

Before reading this article I am expecting a basic knowledge on the react native and nodeJS from you .The code snippets are little difficult to understand for a very beginner, but I tried to make them as easy as I can.Sorry for that

There are many packages available in react-native which supports file upload , and many are there to receive an uploaded file in nodeJS. In case of react-native all of them are depend on xhr requests/fetch api implementations .So its better to go with the vanilla fetch API provided by react native.Its awesome and supports multipart/form-data. In nodeJS there is a middleware called multer which can parse the form data easily and set it in the request object (It can even upload the file to a folder too ) .So Here I am explaining a basic file upload with options to choose image from gallery or directly from camera and read it from a server built with nodeJS

Server configuration

Lets do the server part first.In nodeJS I have used the mighty express framework.Along with the multer middleware. Multer can read the multipart form data and convert set the file data in the req.file attribute, which makes our life far easier.So here is the code for the upload route.In the below snippet we will write the code to initiate the upload route and use multer to save the uploaded files to a folder named upload , and read its contents with fs module by nodeJS

var fs = require('fs');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' }); //setting the default folder for multer
//other imports and code will go hereapp.post('/upload',upload.single('fileData'), (req, res,next) => {
console.log(req.file);//this will be automatically set by multer
console.log(req.body);
//below code will read the data from the upload folder. Multer will automatically upload the file in that folder with an autogenerated name
fs.readFile(req.file.path,(err, contents)=> {
if (err) {
console.log('Error: ', err);
}else{
console.log('File contents ',contents);
}
});
});

Client Configuration

Now is the time to setup the react native environment as explained in the react native official site.Its good to go with the native code method (https://facebook.github.io/react-native/docs/getting-started.html and select Building Projects with Native Code).Once its setup successfully install the react-native-image-picker . Its the best plugin i have ever found for working with image selection from camera and gallery.Once its setup then make a button which can be used to initiate the image selection.With the below code I am uploading the file directly to server once the user makes selection of image.But you can use the component state to save the selected file details and initiate the file upload on click of another button .To do that just move the last else block of code to a function.

import  ImagePicker from 'react-native-image-picker'; <!--OTHER CODES and render will go here --><TouchableHiglight onPress={()=>{
var options = {
title: 'Select Image',
storageOptions: {
skipBackup: true,
path: 'images'
}
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}else {
console.log('User selected a file form camera or gallery', response);
const
data = new FormData();
data.append('name', 'avatar');
data.append('fileData', {
uri : response.uri,
type: response.type,
name: response.fileName
});
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
};
fetch("http://localhost:3000/" + "upload", config)
.then((checkStatusAndGetJSONResponse)=>{
console.log(checkStatusAndGetJSONResponse);
}).catch((err)=>{console.log(err)});
}
}}

voila !! .Thats it.Now you got the file in server.

--

--