我尝试将此单文件下载一个接一个地更改为多文件下载,而不是zip。每次我使用此代码时,它只下载第一个文件(但循环继续)。
我认为这是因为
httpServletResponse.setContentType(mimeType);
我试图以其他方式解决这个问题,但没有任何效果。
@Override
public void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
List<Example> examples = exampleService.findAll();
for (Example example : examples) {
try {
Blob blob = new SerialBlob(example.getFileContent());
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
String mimeType = example.getContentType();
if (mimeType == null) {
mimeType = "application/octet-stream";
}
httpServletResponse.setContentType(mimeType);
httpServletResponse.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", example.getFileName());
httpServletResponse.setHeader(headerKey, headerValue);
OutputStream outputStream = httpServletResponse.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}