Edit:我已经编辑了Java代码,使其能够生成zip文件,但当通过UI下载时,它似乎不起作用,并出现了下面提到的错误。
我最近做了一个代码,应该使一个文件列表到一个zip文件,并在发送AJAX请求后在浏览器中下载它,但经过几天的尝试,结果仍然是一个zip文件,要么有:
- 试图将文件指针移到文件开头之前 *
- 或**
- 无法将文件作为[zip]存档打开。不是存档。*
我希望有人能告诉我哪里错了?
下面是代码的ajax:
$.ajax({
type: "POST",
url: url,
contentType: "application/xml",
data: xmlString,
async: false,
success: function(response, status, jqXHR) {
var filename = "";
var disposition = jqXHR.getResponseHeader("content-disposition");
if (disposition && disposition.indexOf("attachment") !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, "");
}
}
var blob = new Blob([response], {type: "application/octet-stream"});
var link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
link.remove();
},
error: function(error) {
console.log(error);
}
});
下面是处理请求的java代码:
File path = new File(fullPath);
if(path.exists() && !path.isDirectory()) { path.delete(); }
File[] files = path.listFiles((dir, name) -> filesToDownload.contains(name));
if (files.length == 0) {
throw new IllegalArgumentException("No files in path " + path.getAbsolutePath());
}
FileOutputStream fos = new FileOutputStream(fullPath+"download.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
for (File zipThis : files) {
FileInputStream fis = new FileInputStream(zipThis);
ZipEntry zipEntry = new ZipEntry(zipThis.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[2048];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
fileBytes = Files.readAllBytes(Paths.get(fullPath+"download.zip"));
headers.setContentType(MediaType.parseMediaType("application/zip"));
headers.setContentDispositionFormData("attachment", "download.zip");
headers.setContentLength(fileBytes.length);
return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
我希望有人能告诉我我做错了什么
1条答案
按热度按时间ogq8wdun1#
内容长度
根据http规范(https://www.rfc-editor.org/rfc/rfc2616#第14.13节)
应用程序应该使用这个字段来指示消息体的传输长度,除非4.4节中的规则禁止这样做。
所以你应该试试
MIME类型应用程序/zip
应使用
application/zip
作为内容类型