Java使用流实现浏览器自动下载文件(附前端请求代码)

一、注意事项

1.需要注意后端的响应头设置,告诉浏览器下载文件类型(Content-Type)以及文件名称。

2.不同环境下中文路径以及文件名会出现乱码情况

路径解决:

filePath = new String((filePath).getBytes("ISO8859-1"),"UTF-8");

文件名解决:

response.setHeader("Content-Disposition","attachment;filename"+java.net.URLEncoder.encode(fileName,"UTF-8"));

response.setHeader("Content-Disposition",String.format("attachment;filename=\"%s\"",fileName));

3.前端必须使用http请求,而不能使用ajax请求

因为js的ajax函数的返回类型只有xml、text、json、html等类型,没有“流”类型,所以不能够使用相应的ajax函数进行文件下载。但可以用form提交参数,并返回“流”类型的数据。

二、代码

后端:

FileUtil.java

/*
*@param response 请求的相应
*@param fileName 文件名
*@param filePath 文件路径
*/
public void downloadFile(HttpServletResponse response,String fileName,String filePath) throws Exception{
    response.setContentType("application/x-msdownload");
    response.setHeader("Content-Disposition","attachment;filename"+java.net.URLEncoder.encode(fileName,"UTF-8"));
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try{
        ServletOutputStream output = response.getOutputStream();
        bis = new BufferedInputStream(new FileInputStream(filePath));
        bos = new BufferedOutputStream(output);
        byte[] buff = new byte[2048];
        int bytesRead;
        while(-1 != (bytesRead = bis.read(buff,0,buff.length))){
            bos.write(buff,0,bytesRead);
        }
    }catch(Exception e){
        throw e;
    }finally{
        if(bis!=null){
            bis.close();
        }
        if(bos!=null){
            bos.close();
        }
    }
}

FileController.java

@GetMapping("/download")
public void getFile(@RequesParam String fileUrl,HttpServletResponse response) throws Exception{
    String fileName = "报告.docx";
    downloadFile(response,fileName,fileUrl);
}

前端:

前端请求代码

function download(id){
	var urlStrl ="/download";
	var inputValue1 = 'xxxx/xxxx.docx'; 
	var form = $('<form></form>');       
	form.attr('style', 'display:none');        
	form.attr('target', '_blank');      //设置_blank后,下载会在新窗口打开,同时保留原来的窗口   
	form.attr('method', 'get');       
	form.attr('action', urlStrl);
	var input = $('<input type="text" name="fileUrl" id="param1" />'); 
	input.attr('value', inputValue1); 
	form.append(input);   
	$(document.body).append(form);  
	form.submit();    
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值