AppDividend
Latest Code Tutorials

React js Laravel File Upload Tutorial

1,529

Get real time updates directly on you device, subscribe now.

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.

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.

Related Posts
1 of 14
// 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.

Leave A Reply

Your email address will not be published.

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