欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

vue3 +axios 文件上传和下载

最编程 2024-03-02 20:47:47
...

Vue3 + Axios 文件上传及下载

在 Vue3 中,与后端进行文件上传和下载是一个常见需求。本文将介绍如何使用 Axios 进行文件上传和下载,以及如何在 Vue3 项目中实现这些功能。

文件上传

1. 后端准备

首先,我们需要在后端准备接口来处理文件上传。这里以 Node.js 和 Express 为例,使用 multer 中间件来处理文件上传。

安装所需的依赖:

npm install multer

在后端的路由中引入 multer 并配置上传的目标路径和文件名:

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

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

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

2. 前端实现

在 Vue3 项目中,我们使用 Axios 来发送文件上传请求。首先,在项目目录下安装 Axios:

npm install axios

然后,在需要上传文件的组件中引入 Axios:

import axios from 'axios';

接下来,创建一个 uploadFile 方法来处理文件上传请求:

methods: {
  async uploadFile() {
    const file = this.$refs.fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await axios.post('/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      console.log(response.data);
    } catch (error) {
      console.error(error);
    }
  },
}

在 HTML 模板中,我们需要添加一个文件上传的输入框和一个触发上传的按钮:

<input ref="fileInput" type="file" accept="image/*" />
<button @click="uploadFile">上传文件</button>

这样,当用户选择文件后点击上传按钮,文件将被发送到后端进行处理。

文件下载

1. 后端准备

在后端,我们需要提供一个接口来供前端下载文件。这里以 Express 框架为例,假设我们要下载的文件在 uploads/ 目录下。

在后端路由中添加下载文件的接口:

app.get('/download', (req, res) => {
  const filePath = 'uploads/example.txt';
  res.download(filePath);
});

2. 前端实现

在 Vue3 项目中,我们可以使用 a 标签的 download 属性来实现文件下载。首先,在需要下载文件的组件中创建一个 downloadFile 方法:

methods: {
  downloadFile() {
    const link = document.createElement('a');
    link.href = '/download';
    link.download = 'example.txt';
    link.click();
  },
},

在 HTML 模板中添加一个下载按钮,并调用 downloadFile 方法:

<button @click="downloadFile">下载文件</button>

这样,当用户点击下载按钮时,文件将被下载到本地。

结语

通过使用 Vue3 和 Axios,我们可以很方便地实现文件上传和下载功能。在文件上传中,我们使用 FormData 对象将文件数据发送到后端;在文件下载中,我们使用 download 属性和 a 标签来实现下载功能。这两个功能在实际开发中都是非常常见的,掌握它们可以让我们更好地完成前后端的交互。

以上就是关于 Vue3 + Axios 文件上传及下载的科普文章,希望对你有所帮助!

推荐阅读