Uploading image or other files using React Native and Laravel

Many of us struggle coding upload files or photo features during React Native App development process. In this article, I will show you simple process to upload file with react native app and laravel backend. I will be using Expo framework of react native to keep things simple. If you are new to expo go through the documentation before starting with this tutorial.

First Lets install expo command line tool and create/ initialize a react native project using below commands.

When you initialise project you will get four different templates to choose from. The four options will be blank, blank (TypeScript), tabs (TypeScript), minimal and minimal (TypeScript). We will be using blank (TypeScript).

Now we need to install  file picker and image picker, two dependencies for our project. Installation of these dependencies are very simple, since, we are using expo framework of react native. Run below commands to install the dependencies.

Next, replace the code in App.tsx with the code below :

In the above code, We are using Image picker to pick photo from gallery or Document picker to pick document from Files section of mobile. On clicking the upload button the file is sent to Laravel server using javascript FormData api.

Now lets code the Laravel Server. First we will create a route in routes/api.php by adding below code.

Finally, we will create a FileController.php in app/Http/Controllers directory and add the action below :

In the above code, if request has a file then we are getting the file and its extensions. We are generating a random file name and storing the file with the new file name and its original extension. If everything goes well, we are returning the file path else we return null as path.