How to upload files using Axios in ReactJS + Laravel.

Search for a command to run...

No comments yet. Be the first to comment.
Last week, I encountered issues with my existing Ubuntu setup. It was slow and lagging, and I couldn't resolve the problem. Then, I remembered that my laptop had two operating systems installed: Windows and Linux on separate partitions. Suspecting a ...
Introduction If you want to learn about how to use console.log as a professional developer then you have to learn computer property names. Let's Start Assume that we have 4 different objects and each one is assigned to a variable. How can we log thos...

Hello artisans, Today I'll be writing about how to use Query Scopes efficiently in Laravel projects. Query Scopes are very useful to encapsulate the logic you want to apply to database queries while using Models. Let's start with an example and under...

Laravel Sanctum is one way to authenticate different models to use your application but there are many other ways. In this article, I'll be explain how to authenticate team/team members with a Laravel Sanctum. Assume that we have following Model; cla...
Introduction: Managing forms in web applications can be a complex task, especially when dealing with validation rules, error handling, and form submissions. The React useForm plugin library offers a powerful and elegant solution to simplify form mana...

Today I am going to write about how to upload files using Axios in ReactJS + Laravel Framework.
If you already reading this article that means you know what is Axios and you couldn't figure out how to upload files with it. Don't worry it's so simple and I am going to show you an example as well.
Let's assume we have created a simple Form component which contains a simple input element with the type of file and a button to submit the form. Of course, we will not directly submit the form instead we are going to use Axios to handle this and the page will not be redirected to some URL.
import React, {useState} from 'react';
import axios from 'axios';
const Form = () => {
// state to store the selected file.
const [selectedFile, setSelectedFile] = useState(null);
const handleSubmit = async (event) => {
event.preventDefault();
// Create a FormData object
const formData = new FormData();
// Append file to the formData object here
formData.append("selectedFile", selectedFile);
try {
// We will send formData object as a data to the API URL here.
const response = await axios.post("/api/upload/file", formData, {
headers: {"Content-Type": "multipart/form-data"}
}).then((res) => {
alert("File Uploaded Successfully");
}).catch((error) => {
alert("Error")
});
} catch (error) {
console.log(error)
}
}
const handleFileSelect = (event) => {
// we only get the selected file from input element's event
setSelectedFile(event.target.files[0])
}
return (
<form onSubmit={handleSubmit}>
<input type="file" onChange={handleFileSelect}/>
<input type="submit" value="Upload File"/>
</form>
)
};
export default Form;
Let's break the above solution into multiple steps
First, we created a state called selectedFile using useState() hook and we use this state to store the currently selected file.
Secondly, we set handleFileSelect function to the onChange handler of the input element, thus whenever we select a file then handleFileSelect function will be invoked and it sets the selected file into the selectedFile state.
Third, we set handleSubmit function as the onSubmit handler of the form element, and whenever we press Upload File button the code we write inside handleSubmit function is executed.
Fourth, in the handleSubmit function we created FormData object and append the file in the selectedFile state to this object.
Fifth, as we going to send a file to the server we tell Axios that we need this FromData object to be encoded, otherwise the server will not catch the file. In order to do that, we set headers: { "Content-Type": "multipart/form-data" } to the config of the Axios object.
Caution!!! What about if we want to send PUT request with Axios, does the file will be uploaded? The answer is no!
If you want to send a PUT request then you have to send a POST request but specify the actual method you want to send is PUT request.
formData.append("_method", "PUT"); //this only works in Laravel Framework, didn't tried on other Frameworks.
Up to here, we have done with Client side and now we will write a simple code to catch the file on the Back-End and upload it to the our file storage. I am using Laravel Framework on the back-end and I'll show you the example with it.
if ($request->file('selectedFile')) {
$uploadedFile = $request->file('selectedFile');
if ($uploadedFile) {
$filename = Str::uuid() . '.' . $uploadedFile->getClientOriginalExtension();
Storage::disk('public')->putFileAs('uploadedFiles/', $uploadedFile, $filename);
}
}
The above code, checks if the request has a file in the selectedFile variable, and if the file exists, it uploads the file into the uploadedFiles folder in the public storage of the application.