spring boot 解决图片 ,txt点击路径等直接打开而无法下载的问题

本文详细介绍了一种前后端结合的文件下载方案。在前端,使用HTML5的download属性触发下载;在后端,通过SpringMVC的Controller处理下载请求,利用HttpURLConnection从远程服务器获取文件,并将文件流返回给客户端进行下载。该方案适用于需要从远程服务器下载文件的场景。

摘要生成于 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();    
} 

转自https://blog.youkuaiyun.com/qq_37121548/article/details/80895881

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值