When using Axios for file uploads, it's common to use the FormData object to construct form data and send a POST request with Axios. Here are the specific implementation steps:
-
Create a
FormDataobject: This object is used to construct key-value pairs, similar to a standard form submission, where you can include file objects. -
Append file data: Use the
appendmethod ofFormDatato add the file to the form data. -
Send the request: Initiate a
POSTrequest using Axios and pass theFormDataobject as the request body. -
Set request headers (optional): When sending the request, you can set
Content-Typetomultipart/form-data, but typically browsers automatically set the correctContent-Typeand include a boundary string, so this step can be omitted.
The following code example demonstrates this:
javascript// Import the axios library import axios from 'axios'; // Prepare the file object to upload, e.g., from an <input type="file"> element const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; // Create a FormData instance const formData = new FormData(); // Append the file data to the FormData instance, 'image' is the field name recognized by the backend formData.append('image', file); // Set Axios request configuration, where you can set headers and other information if needed const config = { headers: { // 'Content-Type': 'multipart/form-data' is typically not needed manually }, onUploadProgress: function(progressEvent) { // Handle upload progress events here const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); console.log(percentCompleted); } }; // Use axios to send a POST request axios.post('URL for uploading files', formData, config) .then(function (response) { // Handle response data console.log('File upload successful:', response); }) .catch(function (error) { // Handle error cases console.error('File upload failed:', error); });
In the above process, you can see how to create a FormData object, append the file, and send it to the server via Axios. This approach is not only used for file uploads but can also handle other types of binary data. Additionally, by listening to the onUploadProgress event, we can obtain upload progress information, providing a better user experience.