热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

springboot+vue实现页面下载文件

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

本文实例为大家分享了springboot+vue页面下载文件的具体代码,供大家参考,具体内容如下

1.前端代码:


downloadFile(row) {
 window.location = "http://localhost:8001/file/downloadFile?taskId=" + row.id;
}

2.后端代码:

package com.gridknow.analyse.controller;


import com.alibaba.fastjson.JSON;
import com.gridknow.analyse.entity.DataInfo;
import com.gridknow.analyse.service.FileService;
import com.gridknow.analyse.utils.Download;
import com.gridknow.analyse.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;


/**
 * @ClassName FileController
 * @Description: TODO
 * @Author Administrator
 * @Date 2020/8/20 14:02
 * @Version TODO
 **/

@Controller
@RequestMapping("/file")
public class FileController {

 @Value("${gridknow.mltc.imgurl}")
 private String imgUrl;

 @Autowired
 private FileService fileService;


 @CrossOrigin
 @RequestMapping(value = "/upload", method = RequestMethod.POST)
 @ResponseBody
 public Result upload(MultipartHttpServletRequest request) {
  List multipartFiles = request.getFiles("file");
  Map map = (Map) JSON.parse(request.getParameter("body"));
  String companyId = request.getParameter("companyId");
  String companyName = request.getParameter("companyName");
  boolean bool = fileService.uploadAndInsert(multipartFiles, map, companyId, companyName);
  if (bool) {
   return new Result(200);
  } else {
   return new Result(500);
  }
 }

 @GetMapping("/downloadFile")
 public ResponseEntity downloadFile(@RequestParam("taskId") String taskId, HttpServletResponse response) {
  DataInfo dataInfo = fileService.queryTaskById(taskId);
  if (dataInfo == null) {
   return null;
  }
  File file = new File(dataInfo.getResponseUrl());
  // 文件下载
  if (file.isFile()) {
   return downloadFile(taskId);
  }
  // 文件夹压缩成zip下载
  if (file.isDirectory()) {
   String parent = file.getParent();
   // 创建临时存放文件夹
   File temDir = new File(parent + "/" + taskId);
   if (!temDir.exists()) {
    temDir.mkdirs();
   }
   // 将需要下载的文件夹和内容拷贝到临时文件夹中
   try {
    Download.copyDir(dataInfo.getResponseUrl(), parent + "/" + taskId);
   } catch (IOException e) {
    e.printStackTrace();
   }
   // 设置头部格式
   response.setContentType("application/zip");
   response.setHeader("Content-Disposition", "attachment; filename="+taskId+".zip");
   // 调用工具类,下载zip压缩包
   try {
    Download.toZip(temDir.getPath(), response.getOutputStream(), true);
   } catch (IOException e) {
    e.printStackTrace();
   }
   // 删除临时文件夹和内容
   Download.delAllFile(new File(parent + "/" + taskId));
  }
  return null;

 }
 
 public ResponseEntity downloadFile(String taskId) {
  DataInfo dataInfo = fileService.queryTaskById(taskId);
  if (dataInfo == null) {
   return null;
  }
  File file = new File(dataInfo.getResponseUrl());
  String fileName = file.getName();
  InputStreamResource resource = null;
  try {
   resource = new InputStreamResource(new FileInputStream(file));
  } catch (Exception e) {
   e.printStackTrace();
  }
  HttpHeaders headers = new HttpHeaders();
  headers.add("Content-Disposition", String.format("attachment;filename=\"%s", fileName));
  headers.add("Cache-Control", "no-cache,no-store,must-revalidate");
  headers.add("Pragma", "no-cache");
  headers.add("Expires", "0");
  ResponseEntity respOnseEntity= ResponseEntity.ok()
    .headers(headers)
    .contentLength(file.length())
    .contentType(MediaType.parseMediaType("application/octet-stream"))
    .body(resource);
  return responseEntity;
 }
}

工具类

package com.gridknow.analyse.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @ClassName Download
 * @Description: TODO
 * @Author Administrator
 * @Date 2020/9/2 9:54
 * @Version TODO
 **/
@Slf4j
public class Download {

 private static final int BUFFER_SIZE = 2 * 1024;

 public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {

  long start = System.currentTimeMillis();
  ZipOutputStream zos = null;
  try {
   zos = new ZipOutputStream(out);
   File sourceFile = new File(srcDir);
   compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
   long end = System.currentTimeMillis();
   log.info("压缩完成,耗时:" + (end - start) + " ms");
  } catch (Exception e) {
   throw new RuntimeException("zip error from ZipUtils", e);
  } finally {
   if (zos != null) {
    try {
     zos.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }


 /**
  * 递归压缩方法
  *
  * @param sourceFile  源文件
  * @param zos    zip输出流
  * @param name    压缩后的名称
  * @param KeepDirStructure 是否保留原来的目录结构, true:保留目录结构;
  *       false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
  * @throws Exception
  *
  */

 private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
   throws Exception {

  byte[] buf = new byte[BUFFER_SIZE];
  if (sourceFile.isFile()) {
   // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
   zos.putNextEntry(new ZipEntry(name));
   // copy文件到zip输出流中
   int len;
   FileInputStream in = new FileInputStream(sourceFile);
   while ((len = in.read(buf)) != -1) {
    zos.write(buf, 0, len);
   }
   // Complete the entry
   zos.closeEntry();
   in.close();
  } else {
   File[] listFiles = sourceFile.listFiles();
   if (listFiles == null || listFiles.length == 0) {
    // 需要保留原来的文件结构时,需要对空文件夹进行处理
    if (KeepDirStructure) {
     // 空文件夹的处理
     zos.putNextEntry(new ZipEntry(name + "/"));
     // 没有文件,不需要文件的copy
     zos.closeEntry();
    }
   } else {
    for (File file : listFiles) {
     // 判断是否需要保留原来的文件结构
     if (KeepDirStructure) {
      // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
      // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
      compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
     } else {
      compress(file, zos, file.getName(), KeepDirStructure);
     }
    }
   }
  }
 }

 /**
  * 拷贝文件夹
  *
  * @param oldPath 原文件夹
  * @param newPath 指定文件夹
  */
 public static void copyDir(String oldPath, String newPath) throws IOException {
  File file = new File(oldPath);
  //文件名称列表
  String[] filePath = file.list();

  if (!(new File(newPath)).exists()) {
   (new File(newPath)).mkdir();
  }

  for (int i = 0; i 

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


推荐阅读
  • t-io 2.0.0发布-法网天眼第一版的回顾和更新说明
    本文回顾了t-io 1.x版本的工程结构和性能数据,并介绍了t-io在码云上的成绩和用户反馈。同时,还提到了@openSeLi同学发布的t-io 30W长连接并发压力测试报告。最后,详细介绍了t-io 2.0.0版本的更新内容,包括更简洁的使用方式和内置的httpsession功能。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • Lodop中特殊符号打印设计和预览样式不同的问题解析
    本文主要解析了在Lodop中使用特殊符号打印设计和预览样式不同的问题。由于调用的本机ie引擎版本可能不同,导致在不同浏览器下样式解析不同。同时,未指定文字字体和样式设置也会导致打印设计和预览的差异。文章提出了通过指定具体字体和样式来解决问题的方法,并强调了以打印预览和虚拟打印机测试为准。 ... [详细]
  • 安装mysqlclient失败解决办法
    本文介绍了在MAC系统中,使用django使用mysql数据库报错的解决办法。通过源码安装mysqlclient或将mysql_config添加到系统环境变量中,可以解决安装mysqlclient失败的问题。同时,还介绍了查看mysql安装路径和使配置文件生效的方法。 ... [详细]
  • Final关键字的含义及用法详解
    本文详细介绍了Java中final关键字的含义和用法。final关键字可以修饰非抽象类、非抽象类成员方法和变量。final类不能被继承,final类中的方法默认是final的。final方法不能被子类的方法覆盖,但可以被继承。final成员变量表示常量,只能被赋值一次,赋值后值不再改变。文章还讨论了final类和final方法的应用场景,以及使用final方法的两个原因:锁定方法防止修改和提高执行效率。 ... [详细]
  • 本文介绍了求解gcdexgcd斐蜀定理的迭代法和递归法,并解释了exgcd的概念和应用。exgcd是指对于不完全为0的非负整数a和b,gcd(a,b)表示a和b的最大公约数,必然存在整数对x和y,使得gcd(a,b)=ax+by。此外,本文还给出了相应的代码示例。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • EPICS Archiver Appliance存储waveform记录的尝试及资源需求分析
    本文介绍了EPICS Archiver Appliance存储waveform记录的尝试过程,并分析了其所需的资源容量。通过解决错误提示和调整内存大小,成功存储了波形数据。然后,讨论了储存环逐束团信号的意义,以及通过记录多圈的束团信号进行参数分析的可能性。波形数据的存储需求巨大,每天需要近250G,一年需要90T。然而,储存环逐束团信号具有重要意义,可以揭示出每个束团的纵向振荡频率和模式。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 大连微软技术社区举办《.net core始于足下》活动,获得微软赛百味和易迪斯的赞助
    九月十五日,大连微软技术社区举办了《.net core始于足下》活动,共有51人报名参加,实际到场人数为43人,还有一位专程从北京赶来的同学。活动得到了微软赛百味和易迪斯的赞助,场地也由易迪斯提供。活动中大家积极交流,取得了非常成功的效果。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • 禁止程序接收鼠标事件的工具_VNC Viewer for Mac(远程桌面工具)免费版
    VNCViewerforMac是一款运行在Mac平台上的远程桌面工具,vncviewermac版可以帮助您使用Mac的键盘和鼠标来控制远程计算机,操作简 ... [详细]
  • 原文地址:https:www.cnblogs.combaoyipSpringBoot_YML.html1.在springboot中,有两种配置文件,一种 ... [详细]
  • Windows下配置PHP5.6的方法及注意事项
    本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
author-avatar
蛋壳
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有