单个文件下载Demo (Html+java)

1.前端
var requestUrl = "${ctx}/wms/preEntry/fileDownload?fileName="+row.upFileName+"&forId="+row.forId;
var xhr = new XMLHttpRequest();
//GET请求,请求路径url,async(是否异步)
xhr.open('GET', requestUrl, true);
//设置响应类型为 blob
xhr.responseType = 'blob';
//关键部分
xhr.onload = function (e) {
    //如果请求执行成功
    if (this.status == 200) {
        var blob = this.response;
        var a = document.createElement('a');

        blob.type = "application/octet-stream";
        //创键临时url对象
        var url = URL.createObjectURL(blob);

        a.href = url;
        a.download=row.upFileName;
        a.click();
        //释放之前创建的URL对象
        window.URL.revokeObjectURL(url);
    }
};
//发送请求
xhr.send();

2.后端
/***
* 单个文件下载
*/
@RequestMapping(value = "fileDownload", method = RequestMethod.GET)
@ResponseBody
public void fileDownload(HttpServletResponse response, @RequestParam("fileName") String fileName) throws IOException {
    BufferedInputStream br = null;
    OutputStream out = null;
    try {
        // 格式化拼接资源的相对路径
        String filePath = url + "/" + fileName;
        File file = new File(filePath);
        if (!file.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        br = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
        out = response.getOutputStream();
        while ((len = br.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        out.flush();
        out.close();
        br.close();
    }
}

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值