java下载文件到浏览器默认路径

java下载文件到浏览器默认路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mengmeng2222222
一、controller层代码:

 @RequestMapping("/downExcel")
    @ResponseBody
    public Object downExcel(){
        try {
            File file=ResourceUtils.getFile("classpath:doc"); //获取resources下面的doc下面的文件
            File[] files=file.listFiles();
            return FileUtil.downloadFile(files[0]);  //files[0]是要下载到默认浏览器路径的文件
        } catch (Exception e) {
            return MarkUtil.markRetunMsg(false,"下载失败");
        }
    }

注释:运用spring中的ResourceUtils.getFile读取jar包内文件,也就是获取的是下图中的文件
在这里插入图片描述
二、FileUtil类中的downloadFile方法如下:

 /**
     * 文件下载
     * @param file
     * @throws IOException
     */
    public static ResponseEntity<InputStreamResource>  downloadFile(File file) throws IOException {
        if (file.exists()) {
            FileSystemResource fileSource = new FileSystemResource(file);
            return downloadFile(fileSource.getInputStream(),fileSource.getFilename());
        }
        return null;
    }
    public static ResponseEntity<InputStreamResource> downloadFile(InputStream in,String fileName) {
        try {
            byte[] testBytes = new byte[in.available()];
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", MarkUtil.convertFileName(fileName)));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentLength(testBytes.length)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(in));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

三、MarkUtil类中的convertFileName方法如下:

/**
 * chinese code convert
 * @param fileName
 * @return
 */
public static String convertFileName(String fileName) {
        if(isContainChinese(fileName)) {
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }

亲测有效!!!!!如果对你有帮助了,一定要点个赞哇,整理不易。

可以转载,但是务必加上来源,谢谢!

  • 13
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值