zoukankan      html  css  js  c++  java
  • java中使用springmvc实现下载文件

    下载文件具体实现代码:

    public class TestDownload{
      public HttpServletRequest request;
      public HttpServletResponse response;
    
      //下载文件
      public static void downLoadFile(){
        String downloadFileName = "下载后文件名_TEST.xlsx";
    
           FileInputStream inputStream = null;
           OutputStream outputStream = null;
           File file = null;
           try {
               file = new File(getFilePath(request));
               if (!file.exists()) {
                  log.info("日报文件不存在,请重新导出数据");
               } else {
                  inputStream = new FileInputStream(file);
                  response.setContentType("application/txt;charset=utf-8");
                  response.setHeader("Content-Disposition",
                         "attachment;Filename=" + new String(downloadFileName.getBytes("GB2312"), "ISO8859-1"));// 设置下载后文件的名字、防止中文乱码
    
                  outputStream = response.getOutputStream();
                  byte[] bytes = new byte[1024];
                  int len = 0;
                  while ((len = inputStream.read(bytes)) > 0) {
                      outputStream.write(bytes, 0, len);
                  }
               }
          } catch (IOException e) {
                 log.error("文件下载异常:", e);
             } finally {
                 try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (outputStream != null) {
                        outputStream.close();
                    }
                 } catch (IOException e) {
                    log.error("下载日报中关闭流异常 :{} ", e);
                 }
             }
      }
    //获取服务器文件路径
      private String getFilePath(HttpServletRequest request) {
           String fileName = "服务器文件.xlsx";
           String projectPath = request.getSession().getServletContext().getRealPath("/downloadfile/tset");
           return projectPath + "/" + fileName;
        }
    }

     

  • 相关阅读:
    定时任务时间表达式的规则(自己总结)
    本地vagrant配置虚拟域名的坑
    商派onex本地部署无法进入的问题
    一周一篇文章,立贴为证
    Ecshop安装的坑,建议不要使用!
    MYSQL查询语句优化
    .gitignore文件
    剖析Disruptor:为什么会这么快?(二)神奇的缓存行填充
    Disruptor 为什么这么快?
    一篇文章让你成为 NIO 大师 - MyCAT通信模型
  • 原文地址:https://www.cnblogs.com/whx20100101/p/10519381.html
Copyright © 2011-2022 走看看