互联网技术 · 2024年2月20日

Vue实现文件流下载的前后端代码

这篇文章主要为大家详细介绍了vue实现下载文件流完整前后端代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

使用Vue时,我们前端如何处理后端返回的文件流

首先后端返回流,这里我把流的动作拿出来了,我很多地方要用

/**
 * 下载单个文件
 *
 * @param docId
 */
 @GetMapping(“/download/{docId}”)
 public void download(@PathVariable(“docId”) String docId,
       HttpServletResponse response) {
  outWrite(response, docId);
 }
 
 /**
 * 输出文件流
 * @param response
 * @param docId
 */
 private void outWrite(HttpServletResponse response, String docId) {
  ServletOutputStream out = null;
  try {
   out = response.getOutputStream();
   // 禁止图像缓存。
   response.setHeader(“Pragma”, “no-cache”);
   response.setHeader(“Cache-Control”, “no-cache”);
   response.setDateHeader(“Expires”, 0);
   byte[] bytes = docService.downloadFileSingle(docId);
   if (bytes != null) {
    MagicMatch match = Magic.getMagicMatch(bytes);
    String mimeType = match.getMimeType();
    response.setContentType(mimeType);
    out.write(bytes);
   }
   out.flush();
  } catch (Exception e) {
   UnitedLogger.error(e);
  } finally {
   IOUtils.closeQuietly(out);
  }
 }

前端这里我引入了一个组件 js-file-download

npm install js-file-download –save

然后在Vue文件中添加进来

import fileDownload from “js-file-download”;

 // 文档操作列对应事件
 async handleCommand(item, data) {
  switch (item.key) {
  case “download”:
   var res = await this.download(data);
   return fileDownload(res, data.name);
  …
  default:
  }
  // 刷新当前层级的列表
  const folder = this.getLastFolderPath();
  this.listClick(folder.folderId, folder.name);
 },
 // 下载
 async download(row) {
  if (this.isFolder(row.type)) {
  return FolderAPI.download(row.id);
  } else {
  return DocAPI.download(row.id);
  }
 },

docAPI js 注意需要设置responseType

/**
 * 下载单个文件
 * @param {*} id
 */
const download = (id) => {
 return request({
 url: _DataAPI.download + id,
 method: “GET”,
 responseType: blob
 });
};

这样即可成功下载。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册