当前位置:首页 > VUE

vue文件下载后端实现

2026-03-27 02:33:04VUE

后端实现文件下载

在Vue项目中实现文件下载功能通常需要后端配合,以下是常见的后端实现方式(以Node.js为例):

基于Express框架的实现

const express = require('express');
const fs = require('fs');
const path = require('path');

app.get('/download', (req, res) => {
  const filePath = path.join(__dirname, 'files/sample.pdf');
  const stat = fs.statSync(filePath);

  res.setHeader('Content-Length', stat.size);
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', 'attachment; filename=sample.pdf');

  const readStream = fs.createReadStream(filePath);
  readStream.pipe(res);
});

Spring Boot实现

@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() throws IOException {
    Path filePath = Paths.get("files/sample.pdf");
    Resource resource = new InputStreamResource(Files.newInputStream(filePath));

    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=sample.pdf")
        .contentType(MediaType.APPLICATION_PDF)
        .body(resource);
}

前端Vue调用方式

axios({
  method: 'get',
  url: '/download',
  responseType: 'blob'
}).then(response => {
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'sample.pdf');
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
});

处理大文件下载

对于大文件下载,建议使用分块传输:

app.get('/download-large', (req, res) => {
  const filePath = path.join(__dirname, 'files/large-file.zip');
  const stat = fs.statSync(filePath);

  res.writeHead(200, {
    'Content-Length': stat.size,
    'Content-Type': 'application/zip',
    'Content-Disposition': 'attachment; filename=large-file.zip'
  });

  const readStream = fs.createReadStream(filePath);
  readStream.pipe(res);
});

安全注意事项

设置适当的权限检查:

app.get('/download-secure', authenticateUser, (req, res) => {
  if (!req.user.hasPermission('download')) {
    return res.status(403).send('Forbidden');
  }

  // 正常下载逻辑
});

性能优化技巧

使用流式传输避免内存压力:

app.get('/download-optimized', (req, res) => {
  const filePath = path.join(__dirname, 'files/large-file.zip');
  const readStream = fs.createReadStream(filePath);

  res.setHeader('Content-Disposition', 'attachment; filename=large-file.zip');
  readStream.pipe(res);

  readStream.on('error', (err) => {
    res.status(500).send('File transfer error');
  });
});

常见问题解决

处理中文文件名乱码:

res.setHeader('Content-Disposition', 
  `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`);

实现进度显示(前端):

vue文件下载后端实现

axios({
  method: 'get',
  url: '/download',
  responseType: 'blob',
  onDownloadProgress: progressEvent => {
    const percentCompleted = Math.round(
      (progressEvent.loaded * 100) / progressEvent.total
    );
    console.log(percentCompleted + '%');
  }
})

标签: 后端文件
分享给朋友:

相关文章

css文件怎么制作

css文件怎么制作

创建CSS文件的基本步骤 CSS文件用于定义网页的样式,可以与HTML文件分离,便于管理和维护。以下是创建CSS文件的方法: 新建文本文件 使用任意文本编辑器(如Notepad++、VS Code、…

如何编译react文件

如何编译react文件

编译 React 文件的方法 使用 Create React App (CRA) Create React App 是官方推荐的快速搭建 React 项目的工具,内置了 Babel 和 Webpack…

vue实现文件功能

vue实现文件功能

Vue 实现文件上传功能 使用 Vue 实现文件上传功能可以通过原生 HTML 的 <input type="file"> 结合 Vue 的事件处理和 HTTP 请求库(如 Axios)来…

vue预览文件实现

vue预览文件实现

实现文件预览功能 在Vue中实现文件预览功能可以通过多种方式完成,具体取决于文件类型(图片、PDF、文档等)和需求。以下是几种常见实现方法: 图片文件预览 使用HTML5的FileReader AP…

vue 实现文件地址

vue 实现文件地址

Vue 实现文件下载功能 在Vue中实现文件下载功能通常可以通过前端直接触发下载或通过后端API返回文件流。以下是几种常见方法: 前端直接下载(适用于公开URL) 对于已知的公开文件URL,可以直接…

vue实现文件导入导出

vue实现文件导入导出

Vue 文件导入 在 Vue 中实现文件导入通常通过 <input type="file"> 元素结合 FileReader API 完成。 <template> <…