前端 Vue 后端返回流,前端通过流进行下载

前端写法

    //文件下载
    async handleDownload(row) {
      try {
        // 假设文件是通过 GET 请求获取的,url 为文件资源的 API 地址
        const response = await downloadFile(row.id);
        // if (!response.ok) {
        //   throw new Error('网络错误,文件下载失败');
        // }
        // 获取文件内容(Blob)
        const blob = await response;
        if(blob.size == 0){
          this.$modal.msgError("文件不存在!");
          return;
        }
        // 通过 Blob 创建下载链接
        const url = URL.createObjectURL(blob);
        // 创建一个虚拟的 <a> 标签来触发下载
        const a = document.createElement("a");
        a.href = url;
        // 设置下载文件名(你可以从响应中动态获取文件名)
        a.download = row.fileName; // 可以修改为从响应头中获取文件名,例如 response.headers.get('Content-Disposition'
        // 触发下载
        a.click();
        // 释放 Blob URL
        URL.revokeObjectURL(url);
      } catch (error) {
        console.error("文件下载失败:", error);
      }
    },
	
export function downloadFile(id) {
  return request({
    url: '/file/downloadFile/' + id,
    method: 'get',
    responseType: 'blob'
  })
}

后端响应

try {
     // 设置响应头
     response.setContentType(contentType);
     response.setCharacterEncoding("UTF-8");
     response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
     response.setContentLengthLong(fileLength);
	 // 使用 IOUtils 进行文件流拷贝
     try (OutputStream outputStream = response.getOutputStream()) {
          IOUtils.copy(inputStream, outputStream);
       		}
      } catch (IOException e) {
            e.printStackTrace();
            log.info("文件下载出错:" + e.getMessage());
    }
posted @ 2025-01-07 17:18  小侯学编程  阅读(479)  评论(0)    收藏  举报