Home Web Front-end Vue.js Analysis of Vue and server-side communication: how to implement file upload

Analysis of Vue and server-side communication: how to implement file upload

Aug 10, 2023 pm 04:32 PM
vue File Upload Server side communication

Analysis of Vue and server-side communication: how to implement file upload

Analysis of communication between Vue and the server: How to implement file upload

Overview:
In Vue development, communication with the server is a very critical link . Implementing the file upload function is one of the common requirements in development. This article will combine code examples to explore how to implement the file upload function in Vue.

1. Front-end preparation
1. Create a Vue project and introduce necessary dependencies:
Enter the project directory in the terminal and execute the following command to create a Vue project:

vue create file-upload-demo
Copy after login

Then Enter the project directory and install axios and element-ui:

cd file-upload-demo
npm install axios element-ui
Copy after login

2. Configure the file upload component:
Create the FileUpload.vue file in the src/components directory and write the following basic code:

<template>
  <div>
    <el-upload action="/api/upload" :auto-upload="false" :on-change="handleFileChange">
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
export default {
  methods: {
    handleFileChange(file) {
      // 处理文件上传逻辑
    }
  }
}
</script>

<style>
</style>
Copy after login

2. Server-side preparations
1. Create a Node.js server:
Create the server.js file in the project root directory and write the following code:

const express = require('express');
const app = express();

app.post('/api/upload', (req, res) => {
  // 处理文件上传
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});
Copy after login

2. Installation is necessary Dependencies:
Enter the project directory in the terminal and execute the following command to install the necessary dependencies:

npm install express multer
Copy after login

Among them, express is used to create the Node.js server, and multer is used to process file uploads.

3. Configure file upload middleware:
Introduce multer in the server.js file and configure file upload middleware:

const multer = require('multer');

const upload = multer({ dest: 'uploads/' });

app.post('/api/upload', upload.single('file'), (req, res) => {
  // req.file 包含上传的文件信息
  // 处理文件上传逻辑
});
Copy after login

Among them, dest is used to specify the temporary file upload Storage path, upload.single() specifies that only a single file can be uploaded, and the uploaded file will be stored in the dest path.

4. Process file upload logic:
Add the business logic of file upload in the server.js file:

app.post('/api/upload', upload.single('file'), (req, res) => {
  // req.file 包含上传的文件信息
  if (!req.file) {
    return res.status(400).json({ message: '请选择要上传的文件' });
  }

  // 执行文件上传后续操作
  // ...

  res.status(200).json({ message: '文件上传成功' });
});
Copy after login

In the above code, first determine whether req.file exists, determine Whether the user selects a file to upload. Then, when the if condition is established, you can perform subsequent operations on the file upload, such as storing the file in the specified directory on the server, or performing other business processing. Finally, a response is returned through res.status(200) to notify the front-end that the file upload is successful.

3. Front-end and server-side communication
In the FileUpload.vue file, add an axios request to achieve communication with the server-side:

import axios from 'axios';

export default {
  methods: {
    handleFileChange(file) {
      const formData = new FormData();
      formData.append('file', file.raw);

      axios.post('/api/upload', formData)
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }
}
Copy after login

In the handleFileChange method, create a FormData object, Use the append() method to add the uploaded file to FormData. Then, send a POST request through the axios.post() method, and send FormData as the request body to the corresponding route on the server side. Finally, obtain the data returned by the server through response.data, or catch the exception when the request fails in catch.

4. Summary
Through the above steps, we successfully implemented the file upload function between Vue and the server. In the Vue project, we configure the el-upload component of element-ui and combine it with axios to send a POST request for file upload. On the server side, we use express and multer to handle the logic of file upload.

I hope this article can bring some help to you in using file upload in Vue development!

The above is the detailed content of Analysis of Vue and server-side communication: how to implement file upload. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

Vue realizes marquee/text scrolling effect Vue realizes marquee/text scrolling effect Apr 07, 2025 pm 10:51 PM

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with &lt;div&gt;. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

See all articles