在Vue中实现文件上传,通常会使用FormData对象来构建一组键值对,表示表单字段和它们的值,然后通过XMLHttpRequest或者axios这样的HTTP客户端库来发送请求。以下是一个基本的文件上传示例:

  1. HTML模板
<template>
  <div>
    <input type="file" @change="handleFileUpload" />
    <button @click="submitFile">上传文件</button>
  </div>
</template>
  1. Vue组件的脚本部分
<script>
export default {
  data() {
    return {
      file: null
    };
  },
  methods: {
    handleFileUpload(event) {
      this.file = event.target.files[0]; // 获取选择的文件
    },
    submitFile() {
      const formData = new FormData();
      formData.append('file', this.file); // 添加文件到表单数据中

      // 使用axios发送请求
      this.axios.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      .then(response => {
        console.log('文件上传成功', response);
      })
      .catch(error => {
        console.error('文件上传失败', error);
      });
    }
  }
};
</script>
  1. 后端接口

后端接口需要能够处理multipart/form-data类型的请求。以下是一个使用Node.js和Express的简单示例:

const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;

// 设置multer的存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')  // 保存的路径,需事先创建
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())  // 文件名
  }
});

const upload = multer({ storage: storage });

app.post('/upload', upload.single('file'), (req, res) => {
  res.send('文件上传成功');
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});

在这个示例中,我们使用了multer库来处理文件上传。multer是一个用于处理multipart/form-data类型的中间件,主要用于上传文件。

注意:在实际应用中,你可能需要添加更多的错误处理和安全检查,比如验证文件类型、大小等。

此外,如果你使用的是Vue 3,代码结构会有所不同,但基本的上传逻辑是相同的。