AppDividend
Latest Code Tutorials

React js Laravel File Upload Tutorial

8

React js Laravel File Upload Tutorial is topic we will discuss today.We will use Laravel 5.6 as a backend and React js as a frontend framework.In this tutorial, we will upload an image from the react js component.First, we install dependencies using npx then download laravel project. npx comes with npm 5.2+ higher.

If you want to learn more about React and Redux then check out this React 16.6 – The Complete Guide (incl. React Router & Redux) course.

React js Laravel File Upload

First, we install the react js project.

Step 1: Install React js Project

Open your terminal and type following command.

npx create-react-app fileuploadapp

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

npm start or yarn start

Now, Development server start.

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

Go to the src  >> components folder and create a new 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 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 add 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 above code you require axios.Turn to your terminal and type following command to add axios.

yarn add axios

Step 4: Install Laravel 5.6

We install Laravel.Change to your terminal and type 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 files.

php artisan make:model Fileupload -m

It will create both model and migration file.

Step 7: Define the schema in the migration file.

Go to the create_fileuploads_table.php file and add the schema into 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 define routes ,we can create 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 image/intervention package.

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

composer require intervention/image

After installing the package, we require to configure into the 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 need to declare the package by the following command.

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

Now, we can use this package in our FileuploadController.php file.

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

Now, we can store a filename in the database using store function in  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)
    {
        //
    }
}

Now, you can start Laravel Development Server.Type following command.

php artisan serve

 

React js File Upload Tutorial

Finally, React js Laravel File Upload Tutorial is over. You can see that image name is stored in the database.

8 Comments
  1. fie says

    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?

    1. Tai Ly says

      You should show me your code first, use any website that can hightlight php code and give me the link so I could help you.

  2. Tai Ly says

    Thanks, your post is awesome 😀

  3. John says

    Works only on image file .. what about docs,excel ,can you help me?

  4. John Navarro says

    It work’s ! would you mind helping me in uploading excel or doc files, please?

    1. mat says

      you managed to do it with excel files?

  5. Fitra says

    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…

  6. Jamin says

    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?

Leave A Reply

Your email address will not be published.

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