我创建了一个 URL,用户可以通过该 URL 下载 zip 文件。我想知道是否需要在服务器端添加某种规定,以便下载 zip 的客户端可以提供对挂起和恢复的支持。
它是用java实现的:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// reads input file from an absolute path
String filePath = "path to my zip file";
File downloadFile = new File(filePath);
FileInputStream inStream = new FileInputStream(downloadFile);
// if you want to use a relative path to context root:
String relativePath = getServletContext().getRealPath("");
System.out.println("relativePath = " + relativePath);
// obtains ServletContext
ServletContext context = getServletContext();
// gets MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
// obtains response's output stream
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inStream.close();
outStream.close();
}
最佳答案
如果您想支持挂起和恢复,则需要添加对部分 GET 的支持,也称为对范围或范围 header 的支持。
RFC2616(第 14.35 节)详细介绍了如何处理范围请求。 https://www.rfc-editor.org/rfc/rfc2616#section-14.35
Tomcat 的默认 servlet 有一个实现,如果您愿意,您可以将其用作起点。 http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/servlets/DefaultServlet.java?view=annotate
关于java - 我们是否需要在服务器端添加规定,以便浏览器中的文件下载可以提供暂停和恢复的便利?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17294334/