zoukankan      html  css  js  c++  java
  • javaweb简单的实现文件下载及预览

    @ResponseBody
        @RequestMapping(value="/downloadFile")
        public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception{
            //解决乱码问题
            String path = request.getParameter("path");
            String fileName = request.getParameter("fileName");
    
            path = MyUtils.isRandomCode(path);
            fileName = MyUtils.isRandomCode(fileName);
    
            try {
    
                String filePath = path+fileName;
    
                //高速浏览器以附件形式下载
                //不同浏览器的编码不同,对中文进行编码,下载时输出名称是文件名
                response.setHeader("Content-Disposition","attachment;filename="+fileName);
                //获取文件的mimetype,如123.txt,他的mimetype就是 txt ,下载时,就以 txt 格式下载
                String mimeType = fileName.substring(fileName.lastIndexOf(".") + 1);    //获取文件后缀,比如是 txt 文件,就是以txt格式下载
                //设置响应的 mimetype
                response.setContentType(mimeType);
    
                //获取response 输出流,用来输出文件
                ServletOutputStream out = response.getOutputStream();
                //接下来进行读取,以输入流的形式读取
                FileInputStream in = new FileInputStream(filePath);
    
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len=in.read(buffer))!=-1){
                    out.write(buffer,0,len);
                }
                in.close();
    
    
            } catch (Exception e) {
                System.out.println("下载错误!");
            }
        }

    这里有一个工具类,就是前端传过来的参数有可能会乱码,所以要判断一下是否乱码,有乱码的话就处理一下

    package com.zhouhe.modules.api.util;
    
    import java.io.UnsupportedEncodingException;
    
    /**
     * 自定义工具类
     * @Author zhouhe
     * @Date 2019/11/15 11:54
     */
    public class MyUtils {
    
        /**
         * 判断是否是乱码,乱码的话进行处理,不乱码直接返回
         * @param code
         * @return
         */
        public static String isRandomCode(String code) throws UnsupportedEncodingException {
            if (!XUtil.isEmpty(code)) {
                //判断是乱码 (GBK包含全部中文字符;UTF-8则包含全世界所有国家需要用到的字符。)
                if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(code))) {
                    code = new String(code.getBytes("ISO-8859-1"), "utf-8"); //转码UTF8
                }
            }
            return code;
        }
    }

    前端可以使用 window.location.href=请求路径,比如:

     

     注意:

    不能使用ajax请求后台下载文件,否则会有问题:

    ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,ajax没法解析后台返回的文件流,所以无法处理二进制流response输出来下载文件,可以在浏览器中的network里面查看访问的地址,找到response一栏就看见 后台返回的数据:

     解决方法:
    文件直接下载(不需要传递参数),可以使用 < a href="/media">点击下载Excel < /a>
    前端需要传递参数(如excel),可以在绑定方法里面 window.location.href=url

    文件预览:

    public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
          response.sendError(404, "File not found!");
          return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
     
        response.reset(); // 非常重要
        if (isOnLine) { // 在线打开方式
          URL u = new URL("file:///" + filePath);
          response.setContentType(u.openConnection().getContentType());
          response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
          // 文件名应该编码成UTF-8
        } else { // 纯下载方式
          response.setContentType("application/x-msdownload");
          response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
          out.write(buf, 0, len);
        br.close();
        out.close();
      }

    要注意在路径前加了file:///,否则会报错 java.net.MalformedURLException: unknown protocol: e

    还有一点就是中文下载或者带空格的话可能会有问题,会出现中文乱码或者变成___,而空格会被截断,处理方式如下:

    response.setHeader("Content-Disposition","attachment;filename="+fileName);
    换成
    response.setHeader("Content-Disposition","attachment; filename="" + new String(fileName.getBytes("gb2312"),"ISO-8859-1") + """);
  • 相关阅读:
    Centos 5.5+PHP5 添加phpjavabrige
    Google /Baidu Ping服务快速收录php
    基站一些信息
    搜索引擎提交入口收集
    druid简单教程
    http关于application/xwwwformurlencoded等字符编码的解释说明
    对比.NET PetShop和Duwamish来探讨Ado.NET的数据库编程模式。
    WinForm RTF生成器
    在 Visual C# .NET 中跟踪和调试
    c#中构建异常处理
  • 原文地址:https://www.cnblogs.com/zhouheblog/p/11996045.html
Copyright © 2011-2022 走看看