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     }
  • 相关阅读:
    Mac使用pip安装Tensorflow
    php之curl get post curl_multi_exec 请求用法
    重新捡起的知识-字节(Byte)、比特(bit)-计算机常识
    Mac打不开Wireshark dyld: Library not loaded: /usr/X11/lib/libcairo.2.dylib
    ViewController生命周期
    转 try catch finally
    VPS centOS搭建gitlab小结
    UIButton小节
    python 统计单词个数,并按个数与字母排序
    GCP 谷歌云平台申请教程
  • 原文地址:https://www.cnblogs.com/guanghe/p/9729364.html
Copyright © 2011-2022 走看看