代码

参数:

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

2.fileName(a.xlsx)

3.编码格式(GBK)

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

代码片.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//控制器
@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.火狐浏览器效果

2.chrome效果,自动下载

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

文件上传

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
  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架构师根本就飘在天空没下来,根本就没想文件上传这一回事

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public String uploadByHttp(HttpServletRequest request) throws Exception{
    String filePath=null;
    List<String> fileNames = new ArrayList<>();
    //创建一个通用的多部分解析器 
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); 
      //判断 request 是否有文件上传,即多部分请求 
      if(multipartResolver.isMultipart(request)){
        //转换成多部分request  
        MultipartHttpServletRequest multiRequest =multipartResolver.resolveMultipart(request); 
        MultiValueMap<String,MultipartFile> multiFileMap = multiRequest.getMultiFileMap();
        List<MultipartFile> fileSet = new LinkedList<>();
        for(Entry<String, List<MultipartFile>> temp : multiFileMap.entrySet()){
          fileSet = temp.getValue();
        }
        String rootPath=System.getProperty("user.dir");
        for(MultipartFile temp : fileSet){
          filePath=rootPath+"/tem/"+temp.getOriginalFilename();
          File file = new File(filePath);
          if(!file.exists()){
            file.mkdirs();
          }
          fileNames.add(temp.getOriginalFilename());
          temp.transferTo(file);
        }
      } 
  }
3、神啊,我正在撸框架,请问HttpServletRequest怎么获取!!!!

(1)在web.xml中配置一个监听

1
2
3
4
5
<listener>
    <listener-class>
      org.springframework.web.context.request.RequestContextListener
    </listener-class>
  </listener>
(2)HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

文件下载(直接用链接下载的不算),这比较简单

1、本地文件下载(即文件保存在本地)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void fileDownLoad(HttpServletRequest request,HttpServletResponse response,String fileName,String filePath) throws Exception {
    response.setCharacterEncoding("UTF-8");
    //设置ContentType字段值
    response.setContentType("text/html;charset=utf-8");
    //通知浏览器以下载的方式打开
    response.addHeader("Content-type", "appllication/octet-stream");
    response.addHeader("Content-Disposition", "attachment;filename="+fileName);
    //通知文件流读取文件
    InputStream in = request.getServletContext().getResourceAsStream(filePath);
    //获取response对象的输出流
    OutputStream out = response.getOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    //循环取出流中的数据
    while((len = in.read(buffer)) != -1){
      out.write(buffer,0,len);
    }
  }
2、远程文件下载(即网上资源下载,只知道文件URI)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static void downLoadFromUrl(String urlStr,String fileName,HttpServletResponse response){ 
     try {
         urlStr=urlStr.replaceAll("\\\\", "/"); 
        URL url = new URL(urlStr);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        //设置超时间为3秒 
        conn.setConnectTimeout(3*1000); 
        //防止屏蔽程序抓取而返回403错误 
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); 
        
        //得到输入流 
        InputStream inputStream = conn.getInputStream();  
         
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
     response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859_1"));
        //获取响应报文输出流对象 
        //获取response对象的输出流
       OutputStream out = response.getOutputStream();
       byte[] buffer = new byte[1024];
       int len;
       //循环取出流中的数据
       while((len = in.read(buffer)) != -1){
          out.write(buffer,0,len);
       }
    } catch (Exception e) {
      e.printStackTrace();
    } 
  }

以上这篇Java后台Controller实现文件下载操作就是小编分享给大家的全部内容了

Java后台Controller实现文件下载操作相关推荐

  1. java下载xlsx文件_Java后台Controller实现文件下载操作

    代码 参数: 1.filePath:文件的绝对路径(d:\download\a.xlsx) 2.fileName(a.xlsx) 3.编码格式(GBK) 4.response.request不介绍了, ...

  2. java后台实现excel文件下载功能

    java后台实现excel文件下载功能  java中对于excel文件的操作,有读取,写入,上传等功能,在对excel文件进行操作时,为了让使用者更加直观的制作excel数据,必然会有下载模板exce ...

  3. JAVA后台Controller/servlet如何获取到从前端传来的参数

    JAVA后台Controller/servlet如何获取到从前端传来的参数 前言: 本次内容是对后台如何获取到前端传来的信息的总结: 1.前端传来数据的格式为form表单形式: 1.1 reqeust ...

  4. java后台Controller下载文件方法

    /*** 导出* @param request* @param response*/@RequestMapping(value="exportInfo")public void e ...

  5. musql数据库定期跑批操作数据库,不必java后台写定时方法去操作。

    我们java后台定期改变后台数据库一般都是写定时器,定期操作.其实还可以数据库里写个定时跑批任务,来操作数据库. 今天在做项目时,需要每天检查数据库,判断一个表里的数据的时间和状态,如果时间过了3天了 ...

  6. 微信小程序+java后台实现支付(java操作)

    支付,在微信小程序上面称为当一个用户使用该小程序,当进入到支付环节,我们需要调用微信支付接口过程,进行一系列的操作,并记录下来. 微信小程序与java接口实现支付操作,大致思路如下: 1.微信小程序调 ...

  7. 《微信小程序》微信小程序用java后台连接数据库进行操作。

    微信小程序与Java后台的通信 一.写在前面 最近接触了小程序的开发,后端选择Java,因为小程序的代码运行在腾讯的服务器上,而我们自己编写的Java代码运行在我们自己部署的服务器上,所以一开始不是很 ...

  8. java前台传多个id用什么接收_jsp 页面传多个id 到java后台的处理方式

    java 开发中经常遇到 jsp 页面传多个id 到后台处理的情况.比如:批量删除选择内容等....... 我使用的解决的方法两种: jsp 传多个id:使用easyui datagrid 选择多行方 ...

  9. java后台常见问题

    Java后台面试 常见问题 Nginx负载均衡 轮询.轮询是默认的,每一个请求按顺序逐一分配到不同的后端服务器,如果后端服务器down掉了,则能自动剔除 ip_hash.个请求按访问IP的hash结果 ...

最新文章

  1. 毕业,新的开始,撸起袖子加油干!
  2. redis的两种持久化方式详解
  3. 微服务秒杀项目整合网关+feign+redis分离热点商品分别下单示例
  4. 用户选购计算机可分为,助理电子商务师考试试题(1+答案)
  5. 纪中培训总结(2019年9月4~13日)
  6. SourceInsight配置
  7. 跟着动画学习 TCP 三次握手和四次挥手
  8. harbor安装_Harbor简单安装部署,镜像仓库存储使用阿里云OSS
  9. 移动通信原理学习笔记之三——抗衰落和链路性能增强技术
  10. Sql Server :Could not write value to key \Software\Classes\CLSID\...., Verify that you have....
  11. kernel中的日志打印
  12. linux亮度调节指令,Linux Mint 亮度调节——xrandr命令学习
  13. Vue3 中定义ts 对象
  14. python xlsx文件与csv文件转换
  15. 【云速建站如何个人备案】
  16. Windows 剪切板的应用——复制浏览器or本地目录图片
  17. 阿里云服务器购买之后设置密码、安全组、增加带宽、挂载云盘教程
  18. LeetCode-91.解码方法
  19. Windows 10系统点击任务计划程序,提示找不到远程电脑如何处理
  20. vue实现页面全屏、局部全屏等多方式全屏

热门文章

  1. jQuery EasyUI 提示框(Messager)用法
  2. ubuntu安装ssh并开机启动
  3. Java基于springboot开发的漂亮的个人家乡博客系统有论文
  4. 2021-09-19OSPF接口网络类型实验
  5. [QQ飞车]AMD双核CPU可以异常加速QQ飞车,此BUG堪比外挂
  6. 介绍索尼爱立信的Java ME平台
  7. JSP页面查询显示常用模式
  8. 绿茶餐厅再次冲刺港股:年营收23亿 新开59家新餐厅
  9. 全球及中国光罩盒行业研究及十四五规划分析报告
  10. java新闻分页,实现分页功能的JavaBean