繁体   English   中英

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

[英]Zip file getting downloaded without .zip extension in Chrome through Java

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

  4. 该文件已下载到浏览器中,没有任何问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM