Response下载文件工具类

1.前台

发送下载请求

1.form表单提交请求

1.html

尽量不要放中文,可能会乱码

  <%--  用于下载提交请求--%>
  <form id="downloadForm" action="${BASEPATH}annexManage/download" method="post"                     
     type="hidden">
    <input id="filePath" name="filePath" value="" type="hidden"/>
    <input id="fileName" name="fileName" value="" type="hidden"/>
    <input id="extName" name="extName" value="" type="hidden"/>
  </form>

2.js

 $("#downloadForm").submit();

注意: 

不要用ajax请求提交下载,response就算改成了 

"application/x-msdownload; charset=UTF-8")

也不行, 因为ajax是 返回结果的response返回到了你的js代码里, 所以,根本下载不了文件

2.response

response是对于与request的返回

一般后台会向前台返回json字符串,当然也可以返回文件文件流,

 

3.远程文件下载类

文件路径是URL

https://www.baidu.com/img/bd_logo1.png
	public static void downloadRemoteFile(String fileSrc, HttpServletResponse response) throws IOException {
		fileSrc = fileSrc.replace("\\", "/");
		String fileName = FileNameUtils.getName(fileSrc);
		//进行转码, 防止中文名出错
		fileSrc = FileNameUtils.getPath(fileSrc) + URLEncoder.encode(fileName, "utf-8");
		//如果文件名有空格,空格会变成“+”, 故在此将 “+” 还原成空格。
		fileSrc=fileSrc.replaceAll("\\+", "%20");
		URL url = new URL(fileSrc);
		BufferedInputStream in = new BufferedInputStream(url.openStream());
		response.reset();
		response.setContentType("application/x-msdownload; charset=UTF-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20") + "\"");
		OutputStream out = response.getOutputStream();
		IOUtils.copy(in, out);
		in.close();
		out.close();
	}

4.本地文件下载

文件路径是本地路径

	String fileSrc="C:\\Users\\\\Desktop\\中文.xlsx";
public static void  downloadLocalFile(HttpServletResponse response , String path) throws IOException, URISyntaxException {
		Path file= Paths.get(path);
		if(Files.exists(file)){
			response.setContentType("APPLICATION/OCTET-STREAM");
			response.addHeader("Content-Disposition", "attachment; filename="+  URLEncoder.encode(FileNameUtils.getName(fileSrc), "UTF-8") );
			try
			{
				Files.copy(file, response.getOutputStream());
				response.getOutputStream().flush();
			}
			catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值