通过Java在Chrome中下载没有.zip扩展名的Zip文件

时间:2016-09-29 11:30:56

标签: java rest google-chrome servlets zip

  1. 我正在尝试从服务器中的固定位置下载zip文件。
  2. 在我的Rest方法中,我只是从客户端(浏览器)传递文件名。 (请参阅下面的代码)。
  3. 在我的Rest方法中,我将zip文件发送给客户端。

  4. 该文件在浏览器上下载没有任何问题。

  5. 我的问题是zip文件在没有.zip扩展名的浏览器上下载。

    @RequestMapping(value = "/zip/{filePath}", method = RequestMethod.GET)
    public @ResponseBody void downloadZip(@PathVariable("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException {
    
      ServletContext context = request.getServletContext();
      File downloadFile = new File(filePath);
      FileInputStream inputStream = new FileInputStream(downloadFile);
      // get output stream of the response
      OutputStream outStream = response.getOutputStream();
    
      byte[] buffer = new byte[(int) downloadFile.length()];
      int bytesRead = -1;
    
      // write bytes read from the input stream into the output stream
      while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
      }
      // get MIME type of the file
      String mimeType = context.getMimeType(fullPath);
      if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
      }
      System.out.println("MIME type: " + mimeType);
    
      // set content attributes for the response
      response.setContentType(mimeType);
      response.setContentLength((int) downloadFile.length());
    
      response.setHeader("Content-Disposition",
          String.format("attachment; filename=\"%s\"", downloadFile.getName()));
      logger.error("Filename = " + downloadFile.getName());
      inputStream.close();
      outStream.close();
    }
    

    PS:文件下载到某台带有ZIP的机器上,而某些机器上没有ZIP。我只测试过chrome(根据客户要求)。 我认为Chrome浏览器设置存在问题,我需要考虑(只是猜测)。

    有人可以为此提供帮助吗?

    提前致谢....

1 个答案:

答案 0 :(得分:1)

更改设置响应标头和将文件推送到输出流之间的顺序 - 毕竟,标头需要先离开。

[被修改]

  1. “为什么在启动效果时设置HttpServletResponse代码。”
    好吧,简单:客户端应该通过解释HTTP响应头来接收如何处理有效负载的指令。如果没有在开头设置,那么在传输结束时发送这些标题就太晚了。这假设HttpServletResponse实际上会在使用setHeader调用时发送这些标头,这是一个很大的假设 - 我怀疑在调用response.getOutputStream之后实际上不会发送这些标头 - 它响应不太可能缓冲整个有效负载,等待调用者指定这些头。