window.open(url)打开文件,Java程序下载

本文介绍如何通过前端window.open预设下载路径,避免浏览器误识别文件并直接打开。通过encodeURIComponent编码URL,确保所有文件按预期下载,详细展示了使用SpringMVC下载文件的方法,包括设置响应头和字符编码。
摘要由CSDN通过智能技术生成

使用场景:前端使用window.open(url)下载文件,但是浏览器能识别此文件,会打开。不能识别的走下载,于是写代码所有文件都走下载功能

// 对url编码,防止携带特殊字符&,导致获取url不完整
window.open('/download/file?fileName=HelloWorld&fileUrl=' + encodeURIComponent(fileUrl));
           
import org.springframework.util.FileCopyUtils;  

    @GetMapping("/download/file")
    public void downloadFile(String fileUrl, String fileName,HttpServletResponse response) {
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream inputStream = conn.getInputStream();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            FileCopyUtils.copy(inputStream,response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值