spring boot 解决图片 ,txt点击路径等直接打开而无法下载的问题
前台(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();
}
转自https://blog.csdn.net/qq_37121548/article/details/80895881