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;
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
You can see that the image name is stored in the database.
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
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?
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.
Thanks, your post is awesome 😀
Works only on image file .. what about docs,excel ,can you help me?
It work’s ! would you mind helping me in uploading excel or doc files, please?
you managed to do it with excel files?
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…
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?
Also in 2020 usable !!! – also with Laravel 5.8. Thanks a lot for this.
how retrieve file
in react
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…
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.”
Is it possible to upload any kind of files using your script?
Can you tell me the way?
Thanks!
Oh thanks!, would you mind helping me in uploading PDF, please?
Brother webp formate image does not upload if have any solution please mail me
my email suzonice15@gmail.com