java打包图片为zip下载

前端实际数据如下

@Controller
public class QrcodeWebController {

    @RequestMapping(value = "/download",method = RequestMethod.POST)
    public void download(DownloadQrcodeForm form, HttpServletResponse response){
        
        String fileName = TextUtils.urlEncode(form.getZipName()+".zip");

        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" +fileName);

        try {
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            for(int i = 0 ; i < form.getNames().length ; i++){
                ZipEntry zipEntry = new ZipEntry(form.getNames()[i]);
                zos.putNextEntry(zipEntry);
                donwloadFileToZip(form.getImgUrls()[i],zos);
                zos.flush();
            }
            zos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void donwloadFileToZip(String imageUrl,OutputStream os) throws Exception {
        URL url = new URL(imageUrl);
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();

        byte[] buf = new byte[2048];
        int len;
        while ((len = is.read(buf)) != -1) {
            os.write(buf,0,len);
        }
        is.close();
    }
}

 

你可能感兴趣的:(JavaScript,Java)