博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
vue axios+springboot 文件下载
阅读量:7054 次
发布时间:2019-06-28

本文共 2240 字,大约阅读时间需要 7 分钟。

以下是一个比较完整的流程

后端代码如下:

controller:

@RequestMapping(value = "/download", method = RequestMethod.GET)public String downloadData(HttpServletResponse res) {    String data="这是一个下载文件";   //传入数据    File file=new File("文件.txt");    FileUtils.getFile(data.getBytes(),file.getName());    FileUtils.responseTo(file,res);    file.delete();    System.out.println("success");    return "success";}复制代码

工具类如下:

public class FileUtils {public static void getFile(byte[] bfile, String fileName) {    //创建文件    File file=new File(fileName);    try {        if (!file.exists()){file.createNewFile();}        FileOutputStream fos = new FileOutputStream(file);        fos.write(bfile);    } catch (Exception e) {        e.printStackTrace();    }}public static void responseTo(File file, HttpServletResponse res) {  //将文件发送到前端    res.setHeader("content-type", "application/octet-stream");    res.setContentType("application/octet-stream");    res.setHeader("Content-Disposition", "attachment;filename=" + file.getName());    byte[] buff = new byte[1024];    BufferedInputStream bis = null;    OutputStream os = null;    try {        os = res.getOutputStream();        bis = new BufferedInputStream(new FileInputStream(file));        int i = bis.read(buff);        while (i != -1) {            os.write(buff, 0, buff.length);            os.flush();            i = bis.read(buff);        }    } catch (IOException e) {        e.printStackTrace();    } finally {        if (bis != null) {            try {                bis.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }    System.out.println("success");}}复制代码

前端文件接收:

axios({    url: '/gafzpt/capital/download',    method: 'get',    params: {      capitalId: capitalId    },    responseType: 'blob'     //接收类型设置,否者返回字符型  })    .then(res => {           //定义文件名等相关信息      const blob = res.data      const reader = new FileReader()      reader.readAsDataURL(blob)      reader.onload = (e) => {        const a = document.createElement('a')        a.download = `现金流文件`        a.href = e.target.result        document.body.appendChild(a)        a.click()        document.body.removeChild(a)      }    })复制代码

转载于:https://juejin.im/post/5b9297a2f265da0ab5035cac

你可能感兴趣的文章
Tomcat使用与配置
查看>>
接口与抽象类的区别(转)
查看>>
转载:分析apk工具aapt的使用,解析其原理
查看>>
如何向视图插入数据
查看>>
注册和策略模式
查看>>
python 列表
查看>>
第七课作业
查看>>
MEAN实践——LAMP的新时代替代方案(下)
查看>>
CentOS7 下安装 Oracle 12c
查看>>
简单介绍AngularJs Filters
查看>>
jmeter4.0 统计结果次数 BeanShell Sampler,Debug Sampler
查看>>
C和指针学习ing 课后习题练习ing
查看>>
别让bug跑了,通过问题理解ceph的克隆过程
查看>>
Dubbo下一站:Apache顶级项目
查看>>
我说分布式事务之最大努力通知型事务
查看>>
挖机全车无动作是什么故障原因引起的?
查看>>
监狱电视系统设计原则及应用场景
查看>>
JDK 源码阅读 :ByteBuffer
查看>>
python面试题
查看>>
vscode 使用小结
查看>>