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

该博客介绍如何在Spring Boot应用中处理文件下载,特别是针对图片和TXT等直接打开而非下载的情况。通过前端FTL页面和后端Controller配合,实现点击链接触发文件的正确下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前台(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();    
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值