React Laravel File Upload: Everything You Need to Know

To upload a file with React and Laravel, create a React file component and backend it in Laravel. Then use the Axios library to send the file request to the Laravel server and saves the image on the server. In this tutorial, we will upload an image from the react js component. First, we install dependencies using npx, then download the laravel project.

Here is the step-by-step guide.

Step 1: Install React js Project.

Open your terminal and type the following command.

npx create-react-app fileuploadapp 

Move to the project folder by cd command and start the development server using either code.

npm start or yarn start 

Step 2: Create a React component to upload a file.

Go to the src  >> components folder and create a file called FileUploadComponent.js.

//FileUploadComponent.js

import React, { Component } from 'react';

export default class FileUploadComponent extends Component
{
  render()
   {
      return(
        <form>
        <h1>File Upload</h1>
        <input type="file" />
        <button type="submit">Upload</button>
      </form>
      )
   }
}

Next, we can add FileUploadComponent in the App.js file.

//App.js

import React, { Component } from 'react';
import FileUploadComponent from './components/FileUploadComponent';

class App extends Component {
  render() {
    return (
      <div className="App">
          <FileUploadComponent/>      
      </div>
    );
  }
}

export default App;

 

React js File Upload Form

Step 3: Add State and Event in Component.

After adding the state and event in FileUploadComponent.js looks like below.

//FileUploadComponent.js

import React, { Component } from 'react';
import axios, { post } from 'axios';

export default class FileUploadComponent extends Component
{
   constructor(props) {
      super(props);
      this.state ={
        image: ''
      }
      this.onFormSubmit = this.onFormSubmit.bind(this)
      this.onChange = this.onChange.bind(this)
      this.fileUpload = this.fileUpload.bind(this)
    }
    onFormSubmit(e){
      e.preventDefault() 
      this.fileUpload(this.state.image);
    }
    onChange(e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length)
            return;
      this.createImage(files[0]);
    }
    createImage(file) {
      let reader = new FileReader();
      reader.onload = (e) => {
        this.setState({
          image: e.target.result
        })
      };
      reader.readAsDataURL(file);
    }
    fileUpload(image){
      const url = 'http://localhost:8000/api/fileupload';
      const formData = {file: this.state.image}
      return  post(url, formData)
              .then(response => console.log(response))
    }
  
   render()
   {
      return(

         <form onSubmit={this.onFormSubmit}>
        <h1>React js Laravel File Upload Tutorial</h1>
        <input type="file"  onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
      )
   }
}

In the above code, you require axios.

Switch to your terminal and type the following command to add axios.

yarn add axios

Step 4: Install Laravel

We install Laravel. Switch to your terminal and type the following command.

composer create-project laravel/laravel LaravelReactJSFileUpload --prefer-dist 

Step 5: Configure the database.

Add your database credentials in the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelreactfileupload
DB_USERNAME=root
DB_PASSWORD=

Step 6: Create one model and migration file.

php artisan make:model Fileupload -m 

It will create both model and migration files.

Step 7: Define the schema in the migration file.

Go to the create_fileuploads_table.php file and add the schema to it.

public function up()
    {
        Schema::create('fileuploads', function (Blueprint $table) {
            $table->increments('id');
            $table->string('filename');
            $table->timestamps();
        });
    }

Step 8: Define the routes in the api.php file.

Before defining routes, we can create a controller called FileuploadController.php.

php artisan make:controller FileuploadController

Define the following route in the api.php file.

Route::resource('fileupload', 'FileuploadController');

Step 9: Install the image/intervention package.

Reach your terminal and copy the following command to install the intervention/image package.

composer require intervention/image 

After installing the package, we require to configure it into Laravel. So go to the config  >>  app.php file and designate the Intervention Image Provider.

// app.php

'providers' => [
 Intervention\Image\ImageServiceProvider::class,
];

'aliases' => [
 'Image' => Intervention\Image\Facades\Image::class,
]

After this step, we must declare the package using the following command.

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"

We can use this package in our FileuploadController.php file.

Step 10: Store Data in a database using a Store function.

We can store a filename in the database using the store function in the FileuploadController.php file.

//FileuploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Fileupload;

class FileuploadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if($request->get('file'))
       {
          $image = $request->get('file');
          $name = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];
          \Image::make($request->get('file'))->save(public_path('images/').$name);
        }



        $fileupload = new Fileupload();
        $fileupload->filename=$name;
        $fileupload->save();
        return response()->json('Successfully added');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

You can start the Laravel Development Server.

Type the following command.

php artisan serve

React js File Upload TutorialYou can see that the image name is stored in the database.

That’s it.

15 thoughts on “React Laravel File Upload: Everything You Need to Know”

  1. thansk before, its very usefull for me as beginer. i’m trying this code, but im getting an error “Undefined variable: name” in FileuploadController.php.. could u mind to help me, please?

    Reply
  2. Thank you for your tutorial..
    I have to try your post, but when I click the upload button, there is show error in console “Access to XMLHttpRequest has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

    Maybe someone can help me to solve this.
    Thank you very much…

    Reply
  3. Thanks a lot for this, It saved me.

    please how can I delete the uploaded file from the database when a user clicks delete after uploading it?

    Reply
    • Thank you for your tutorial..
      I have to try your post, but when I click the upload button, there is show error in console “Access to XMLHttpRequest has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

      Maybe someone can help me to solve this.
      Thank you very much…

      Reply
  4. I have to try your post, but when I click the upload button, there is show error in console “Access to XMLHttpRequest has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.