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包内文件,也就是获取的是下图中的文件
《java下载文件到浏览器默认路径》
二、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;
    }

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

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

    原文作者:mengmeng233
    原文地址: https://blog.csdn.net/mengmeng2222222/article/details/89914831
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞