您的位置:首页 > 编程语言 > Java开发

通过 html 路径下载服务器文件 (spring boot )解决图片 ,txt等直接打开无法下载的问题

2018-07-03 11:28 811 查看

前台(ftl)

<a href="/file/down?url='html路径'&name='文件名'"  download>下载</a>

后台(controller)

@GetMapping("/file/down")
public void Down(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");//获取要下载的文件名
//第一步:设置响应类型
name = URLEncoder.encode(name, "UTF-8");
resp.setHeader("Content-Disposition", "attachment;filename="+name);
resp.setContentType("application/force-download");//应用程序强制下载
//第二读取文件
String url = req.getParameter("url");
OutputStream out = resp.getOutputStream();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse httpResp = httpclient.execute(httpGet);
try {
HttpEntity httpEntity = httpResp.getEntity();
resp.setContentLength((int)httpEntity.getContentLength());
IOUtils.copy(httpEntity.getContent(), out);
} catch (Exception ex) {
httpclient.close();
}
out.flush();
out.close();
}

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐