Java后台Controller实现文件下载操作

代码

参数:

1.filePath:文件的绝对路径(d:\download\a.xlsx)

2.fileName(a.xlsx)

3.编码格式(GBK)

4.response、request不介绍了,从控制器传入的http对象

代码片.

//控制器
@RequestMapping(UrlConstants.BLACKLIST_TESTDOWNLOAD)
public void downLoad(String filePath, HttpServletResponse response, HttpServletRequest request) throws Exception {
    boolean is = myDownLoad("D:\\a.xlsx","a.xlsx","GBK",response,request);
    if(is)
     System.out.println("成功");
    else
    System.out.println("失败");  
}
//下载方法
public boolean myDownLoad(String filePath,String fileName, String encoding, HttpServletResponse response, HttpServletRequest request){
   File f = new File(filePath);
    if (!f.exists()) {
      try {
        response.sendError(404, "File not found!");
      } catch (IOException e) {
        e.printStackTrace();
      }
      return false;
    }

    String type = fileName.substring(fileName.lastIndexOf(".") + 1);
    //判断下载类型 xlsx 或 xls 现在只实现了xlsx、xls两个类型的文件下载
    if (type.equalsIgnoreCase("xlsx") || type.equalsIgnoreCase("xls")){
      response.setContentType("application/force-download;charset=UTF-8");
      final String userAgent = request.getHeader("USER-AGENT");
      try {
        if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Edge")) {// IE浏览器
          fileName = URLEncoder.encode(fileName, "UTF8");
        } else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
          fileName = new String(fileName.getBytes(), "ISO8859-1");
        } else {
          fileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
        }
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
      } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage(), e);
        return false;
      }
      InputStream in = null;
      OutputStream out = null;
      try {

        //获取要下载的文件输入流
        in = new FileInputStream(filePath);
        int len = 0;
        //创建数据缓冲区
        byte[] buffer = new byte[1024];
        //通过response对象获取outputStream流
        out = response.getOutputStream();
        //将FileInputStream流写入到buffer缓冲区
        while((len = in.read(buffer)) > 0) {
          //使用OutputStream将缓冲区的数据输出到浏览器
          out.write(buffer,0,len);
        }
        //这一步走完,将文件传入OutputStream中后,页面就会弹出下载框

      } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return false;
      } finally {
        try {
          if (out != null)
            out.close();
          if(in!=null)
            in.close();
        } catch (IOException e) {
          logger.error(e.getMessage(), e);
        }
      }
      return true;
    }else {
      logger.error("不支持的下载类型!");
      return false;
    }
  }

实现效果

1.火狐浏览器效果

Java后台Controller实现文件下载操作

2.chrome效果,自动下载

Java后台Controller实现文件下载操作

补充知识:文件上传/下载的几种写法(java后端)

文件上传

1、框架已经帮你获取到文件对象File了

  public boolean uploadFileToLocale(File uploadFile,String filePath) {
    boolean ret_bl = false;
    try {
      InputStream in = new FileInputStream(uploadFile);
      ret_bl=copyFile(in,filePath);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return ret_bl;
  }  
  
  public boolean copyFile(InputStream in,String filePath) {
    boolean ret_bl = false;
    FileOutputStream os=null;
    try {
      os = new FileOutputStream(filePath,false);
      byte[] b = new byte[8 * 1024];
      int length = 0;
      while ((length = in.read(b)) > 0) {
        os.write(b, 0, length);
      }
      os.close();
      in.close();
      ret_bl = true;
    } catch (Exception e) {
      e.printStackTrace();
    }finally{   
        try {
          if(os!=null){
            os.close();
          }
          if(in!=null){
            in.close();
          }
          
        } catch (IOException e) {
          e.printStackTrace();
        }    
    }
    return ret_bl;
  }

}

2、天了个撸,SB架构师根本就飘在天空没下来,根本就没想文件上传这一回事

Java后台Controller实现文件下载操作

扫一扫手机访问