Preface
With the continuous development of modern web applications, file upload has become an indispensable part of user interaction. In this blog, we will discuss in depth how to implement a file upload function in Vue3 and interact with the backend API. We will use Vue3's Composition API (setup syntax sugar) to build our example.
1. Understand the requirements
Before implementing file upload, we need to clarify our needs. Suppose our application allows users to upload their avatars. We need to provide a file selector through which the user can select the file. After selecting the file, the system will upload the file to the backend API and return the uploaded result.
Backend API design
Our backend API usagePOST
Request, path/api/upload
and require the uploaded file to passmultipart/form-data
Form Submit. The response result will contain the URL of the uploaded file and some file information.
2. Create a Vue3 project
If you haven't created a Vue3 project yet, please use the following command to build a new Vue3 project:
npm install -g @vue/cli vue create vue-file-upload cd vue-file-upload
Select the configuration that suits your project and install the dependencies after completion.
3. Write upload components
existsrc/components
Create a directory calledThe new file is the component we handle file uploads.
<template> <div class="file-upload"> <h2>Avatar upload</h2> <input type="file" @change="handleFileChange" /> <button @click="uploadFile" :disabled="!selectedFile">Upload</button> <p v-if="uploadMessage" :class="{ success: isSuccess, error: !isSuccess }">{{ uploadMessage }}</p> </div> </template> <script setup> import { ref } from 'vue'; import axios from 'axios'; const selectedFile = ref(null); const uploadMessage = ref(''); const isSuccess = ref(false); const handleFileChange = (event) => { const file = [0]; if (file) { = file; = ''; // Clear previous messages } }; const uploadFile = async () => { if (!) return; const formData = new FormData(); ('file', ); try { const response = await ('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data', }, }); if () { = 'The file upload was successful! '; = true; } else { = 'The file upload failed, please try again. '; = false; } } catch (error) { = 'An error occurred during the upload process, please try again later. '; = false; } finally { = null; // Reset file input after uploading } }; </script> <style scoped> .file-upload { max-width: 400px; margin: auto; padding: 20px; border: 1px solid #ccc; border-radius: 5px; } .success { color: green; } .error { color: red; } </style>
Code parsing
-
Template section: We created a file selector and a button, when the user selects a file and clicks the "Upload" button,
uploadFile
The method will be called. -
Responsive variables:We use
ref
To create responsive variablesselectedFile
、uploadMessage
andisSuccess
, to manage the file selection status and upload status. -
Event handling:
handleFileChange
Methods are used to process and store files selected by users inselectedFile
middle.uploadFile
The method is responsible for uploading the file to the backend. -
File upload:We use
axios
Library to sendPOST
ask. We append the selected file toFormData
and set the appropriate request header ## 4. Configure Axios
Install in the projectaxios
library for HTTP requests. If you haven't installed it, you can use the following command:
npm install axios
Next, insrc/
Import inaxios
, and can configure the basic API path (assuming your API server is on port 8080 locally).
import { createApp } from 'vue'; import App from './'; import axios from 'axios'; = 'http://localhost:8080'; // Replace with the basic URL of the backend API createApp(App).mount('#app');
5. Integration and testing
In your, import and use
FileUpload
Components:
<template> <div > <FileUpload /> </div> </template> <script setup> import FileUpload from './components/'; </script> <style> /* Add your global style */ </style>
Now you can start your Vue app by running the following command:
npm run serve
Open a browser and accesshttp://localhost:8080
, you should be able to see the file upload component.
6. Backend API example
To demonstrate the integrity of front-end applications, here is a simple back-end API example. You can use the Express framework to handle file uploads.
Initialize a project in a new directory and install the dependencies:
npm init -y npm install express multer cors
const express = require('express'); const multer = require('multer'); const cors = require('cors'); const path = require('path'); const app = express(); const upload = multer({ dest: 'uploads/' }); // The file will be saved in the uploads directory (cors()); ('/api/upload', ('file'), (req, res) => { if (!) { return (400).send({ error: 'Please upload a file' }); } // Return file information const filePath = (__dirname, 'uploads', ); ({ url: filePath, filename: }); }); const PORT = 8080; (PORT, () => { (`Server is running on http://localhost:${PORT}`); });
Start the backend API
Make sure to start the backend server by running the following command in the terminal:
node
7. Summary
In this blog, we demonstrate how to use the Composition API in Vue3 to implement file uploading and interact with the backend API. This approach provides clear and structured code, making it easier to maintain and expand.
This is the article about how to implement file upload function and backend API in Vue3. For more related content related to Vue3 file upload and backend API, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!