我创建了一个下载按钮来获取产品照片的 zip 文件。在 localhost 中测试时它工作正常,但在部署到服务器后不起作用。
没有创建 zip 文件,web 控制台和 catalina 日志中都没有错误消息,什么也没发生……
我一度怀疑是文件大小问题。但是 spring boot 似乎只有最大上传大小,没有下载。 每张照片大小在 50KB 到 150KB 左右,每个 zip 文件最多 5 张照片,所以大小应该不是问题
有没有人遇到过类似的问题?任何建议,将不胜感激!
前端代码(jquery) 我不简单地使用 window.open(link) 的原因是因为 zip 文件名标记了我的后端路径(即 downloadAttachment.zip),所以我做了下面的工作
$("#download").click(function(){
var downloadLink = '<c:url value="/receiving/downloadAttachments.do"/>'
+"?productId=${productId}";
var linkElement = document.createElement("a");
linkElement.href = downloadLink;
linkElement.download = "product_image_${productId}.zip";
document.body.appendChild(linkElement);
linkElement.click();
document.body.removeChild(linkElement);
})
后端代码(java) 当我检查日志时,我意识到控制器根本没有被调用。
@RequestMapping(value="/downloadAttachments", method = RequestMethod.GET)
public void downloadAttachments( HttpServletRequest request, HttpServletResponse response,
@RequestParam(value="productId", required=true)Long productId) throws IOException{
log.debug("/downloadItemAttachments -- productId:"+productId);
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
List<ProductInfo> attachmentList = productInfoService.findByProductId(productId);
int contentLength = 0;
int seq = 1;
if(attachmentList!=null && !attachmentList.isEmpty()){
for(ProductInfo att : attachmentList){
String fileName = "item_"+productId+"_"+seq+".png";
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
//convert base 64 str to image
byte[] bytes = DatatypeConverter.parseBase64Binary(att.getBase64Str());
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
int length;
while ((length = bis.read(bytes)) >= 0) {
log.debug("file size : "+length);
contentLength += length;
zos.write(bytes, 0, length);
}
IOUtils.copy(bis, zos);
zos.closeEntry();
bis.close();
}
log.debug("contentLength -- "+contentLength);
zos.close();
String zipFileName = "product_image_"+productId+".zip";
response.setContentType("application/zip");
response.setStatus(HttpServletResponse.SC_OK);
response.setContentLength(contentLength);
response.setHeader("Content-Disposition","attachment;filename=\""+URLEncoder.encode(zipFileName,"UTF-8")+"\"");
response.flushBuffer();