JAVA实现下载的前后端代码

之前看了很多别人的博客,总是只有一半,基本都只有后端,现在发一个自己实践能用的。
前端代码如下:

function download(url) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.responseType = "blob";    // 返回类型blob
        // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
        xhr.onload = function () {
            // 请完成
            if (this.status === 200) {
                // 返回200
                var blob = this.response;
                var reader = new FileReader();
                reader.readAsDataURL(blob);    
                reader.onload = function (e) {
                    // 转换完成,创建一个a标签用于下载
                    var a = document.createElement('a');
                    // 下载的文件名
                    a.download = '321200_20190521_0001_BILL.RES';
                    a.href = e.target.result;
                    $("body").append(a);    // 修复firefox中无法触发click
                    a.click();
                    $(a).remove();
                }
            }
        };
        xhr.send()
    }

这里的download(url)方法就是向后端请求文件流。url就是后端获取文件流的接口。其中我请求时还传递了文件路径(path)以及文件名(fileName)两个参数。
后端代码:

@RequestMapping(value = "/download",produces = { "application/json" },method = RequestMethod.POST)
    @ResponseBody
    public void download(String path,String fileName, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Pragma", "No-Cache");
        response.setHeader("Cache-Control", "No-Cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("application/msexcel; charset=UTF-8");
        response.setHeader("Content-disposition","attachment; filename=" + URLEncoder.encode(fileName, "GBK"));// 设定输出文件头
        ServletOutputStream out = null;
        FileInputStream in = null; // 读入文件
            in = new FileInputStream(path);
            out = response.getOutputStream();
            out.flush();
            int aRead = 0;
            while ((aRead = in.read()) != -1 & in != null) {
                out.write(aRead);
            }
            out.flush();
            in.close();
            out.close();
    }

这样前端接收到后端的返回后就会开始下载了,还可以在谷歌浏览器中开启选择下载位置。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值