How to Upload Files from React js to Laravel 10 API
In this tutorial, we will see how to upload files from react js to Laravel 10 API, let's assume that we have a react js app and the user wants to update his profile image, so let's see how we can do that.
Get user data from the react js front end
In the front end, we use the form data interface, all we have to do is to append the values and send them to the Laravel API using Axios.
import React from 'react';
import { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { BASE_URL } from '../../Helpers/Url';
import { toast } from 'react-toastify';
import { setCurrentUser } from '../../redux/slices/userSlice';
import axios from 'axios';
export default function ProfileSidebar() {
const [image, setImage] = useState('');
const { user, token } = useSelector(state => state.user);
const dispatch = useDispatch();
const config = {
headers: {
"Content-type": "multipart/form-data",
"Authorization": `Bearer ${token}`,
}
};
const updateProfileImage = async () => {
try {
const formData = new FormData();
formData.append('user_image', image);
formData.append('_method', 'put');
const response = await axios.post(`${BASE_URL}user/update/${user.id}`, formData, config);
dispatch(setCurrentUser(response.data.user));
setImage('');
toast.success("Your profile image has been updated !", {
position: toast.POSITION.TOP_RIGHT
});
} catch (error) {
console.log(error)
}
}
return (
<div className="col-md-4">
<div className="card p-2">
<div className="d-flex flex-column justify-content-center align-items-center">
<img src={user.image_url}
width={150}
height={150}
className="rounded-circle"
alt="Profile Image" />
<div className="input-group my-3">
<input type="file"
name="user_image"
onChange={(e) => setImage(e.target.files[0])}
accept="image/*"
className="form-control" />
<button disabled={!image}
onClick={() => updateProfileImage()}
className="btn btn-sm btn-primary">
Upload
</button>
</div>
</div>
</div>
</div>
)
}
Store data in the database
Next, we get and store data in the UserController.
<?php
namespace App\Http\Controllers\Api;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
class UserController extends Controller
{
/**
* Update user profile
*/
public function updateUserProfile(User $user, Request $request) {
if($request->has("user_image")) {
$path = public_path('storage/images/users/');
if(File::exists($path.$user->profile_image)) {
File::delete($path.$user->profile_image);
}
$user_image = $request->file('user_image');
$user_image_name = time() . '_' . 'user'. '_' . $user_image->getClientOriginalName();
$user_image->storeAs('images/users/', $user_image_name, 'public');
$user->update([
'profile_image' => $user_image_name
]);
}
}
}
Adding the route
Finally, we add the route.
Route::middleware('auth:sanctum')->group(function() {
Route::put('user/update/{user}',[UserController::class,'updateUserProfile']);
});