Table of contents
No headings in the article.
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.