zoukankan      html  css  js  c++  java
  • Java传统下载和SpringMVC下载

     1  /**
     2      * 传统下载
     3      * @param filename 文件名称
     4      */
     5     @RequestMapping(value="download", method={RequestMethod.GET, RequestMethod.POST})
     6     public void download(HttpServletRequest request, HttpServletResponse response, String filename) {
     7         String realpath = request.getServletContext().getRealPath("/");
     8         // 输出文件路径
     9         String filepath = realpath + filedir + "/" + filename;
    10         response.setContentType("application/octet-stream;charset=utf-8");
    11         response.setHeader("Content-Disposition", "attachment;filename=" + filename);
    12         response.addHeader("Pragma", "no-cache");
    13         response.addHeader("Cache-Control", "no-cache");
    14         try {
    15             OutputStream os = response.getOutputStream();
    16             InputStream is = new BufferedInputStream(new FileInputStream(filepath));
    17             byte[] buffer = new byte[4096];
    18             int length = 0;
    19             while((length = is.read(buffer)) > 0) {
    20                 os.write(buffer, 0, length);
    21             }
    22             is.close();
    23             os.close();
    24         } catch (Exception e) {
    25             e.printStackTrace();
    26         }
    27     }
    28 
    29     /**
    30      * SpringMVC下载
    31      * @return 文件名称
    32      */
    33     @RequestMapping(value="graceDownload", method={RequestMethod.GET, RequestMethod.POST})
    34     public ResponseEntity<byte[]> graceDownload(HttpServletRequest request, String filename) {
    35         String realpath = request.getServletContext().getRealPath("/");
    36         // 输出文件路径
    37         String filepath = realpath + filedir + "/" + filename;
    38         byte[] byteArray = null;
    39         try {
    40             byteArray = FileUtils.readFileToByteArray(new File(filepath));
    41         } catch(Exception e) {
    42             e.printStackTrace();
    43         }
    44         HttpHeaders headers = new HttpHeaders();
    45         headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    46         headers.setContentDispositionFormData("attachment", filename);
    47         ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(byteArray, headers, HttpStatus.CREATED);
    48         return responseEntity;
    49     }
  • 相关阅读:
    作业九 主成分分析
    作业八 特征选择
    作业七 逻辑回归应用
    作业六 逻辑回归
    作业五 线性回归算法
    第十四次作业:手写数字识别-小数据集
    第十三次作业:深度学习-卷积
    第七次作业:7.逻辑回归实践
    第十二次作业:垃圾邮件分类2
    第十一次作业:朴素贝叶斯-垃圾邮件分类
  • 原文地址:https://www.cnblogs.com/guanghe/p/9729364.html
Copyright © 2011-2022 走看看