• 浏览器文件下载读取本地文件


    /**
    * 文件下载
    * @param fileName
    * @param filePath
    * @param request
    * @param response
    * @return
    */
    @RequestMapping("/download")
    public String download( String fileName ,String filePath, HttpServletRequest request, HttpServletResponse response){

    response.setContentType("text/html;charset=utf-8");
    try {
    request.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
    }

    java.io.BufferedInputStream bis = null;
    java.io.BufferedOutputStream bos = null;
    String downLoadPath = filePath; //注意不同系统的分隔符
    System.out.println(downLoadPath);

    try {
    long fileLength = new File(downLoadPath).length();
    response.reset();
    response.setContentType("application/x-msdownload;");
    String userAgent = request.getHeader("user-agent").toLowerCase();
    //处理是否是ie浏览器
    if (userAgent.contains("msie") || userAgent.contains("like gecko") ){
    response.setHeader("Content-disposition", "attachment; filename=" + new String(URLEncoder.encode(fileName, "UTF-8")));
    }else {
    response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
    }
    response.setHeader("Content-Length", String.valueOf(fileLength));

    bis = new BufferedInputStream(new FileInputStream(downLoadPath));
    bos = new BufferedOutputStream(response.getOutputStream());
    byte[] buff = new byte[1024];
    // 将数据写入输出流
    int bytesRead;
    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    bos.write(buff, 0, bytesRead);
    }
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    if (bis != null)
    try {
    bis.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    if (bos != null)
    try {
    bos.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    return null;
    }
  • 相关阅读:
    T3java核心API基础类
    java字符编码
    Servlet 1
    T2java面向对象
    T1java语言基础
    Mac OS mysql数据库安装与初始化
    java多线程中注入Spring对象问题
    T4java核心API集合类
    The first day Teddy
    Spring第二节 注入依赖
  • 原文地址:https://www.cnblogs.com/cuiguangpeng/p/12980884.html
Copyright © 2020-2023  润新知