Java后端压缩文件并下载
前端下载文件
//差旅费报销单zip导出 viewModel.get('button9ag').on('click', function () { const prefix = cb.utils.getServiceUrl() debugger let rows= viewModel.getGridModel().getSelectedRows(); if(rows.length === 0){ cb.utils.alert('请先选择数据', 'warring'); return; }; let ids=[]; for(let i=0;i<rows.length;i++){ ids.push(rows[i].id); } const getTableData =async()=>{ httpPost( '/files/billExport/queryBillDataAndAttachment', { json:{ ids: ids } }, { uniform:false, responseType:'blob' } ).then((res)=>{ debugger
//const blob = new Blob([res.data],{type:'application/vnd-ms-excel'}); const blob = new Blob([res.data],{type:'application/zip'}); const a = document.createElement("a"); const URL = window.URL || window.webkitURL; const href = URL.createObjectURL(blob); a.href= href; a.download='差旅费报销单.zip'; document.body.appendChild(a); a.click(); document.body.removeChild(a); window.URL.revokeObjectURL(href); }).catch((error)=>{ debugger cb.utils.alert("error") }) }; getTableData() }) // http请求发送 const httpAjax = (method, url, payload = {},optionData) => { return new Promise((resolve, reject) => { cb.rest.DynamicProxy.create({ ensure: { url: url, method: method, options: { domainKey: 'npic', ...optionData } } }).ensure(payload, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); }; // 提取get请求 const httpGet = (url, payload,optionData) => { return httpAjax('GET', url, payload,optionData); }; // 提取post请求 const httpPost = (url, payload,optionData) => { return httpAjax('POST', url, payload,optionData); };
controller层
@PostMapping("/queryBillDataAndAttachment") public void fileDownload(HttpServletRequest request, HttpServletResponse response, @RequestBody CommonRequestDTO requestDTO) throws Exception { OutputStream outputStream = response.getOutputStream(); fileDownloadService.queryBillDataAndAttachment(requestDTO.getIds(),outputStream); response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); }
service层压缩逻辑
/** * 传入文件file * @param outputStream 输出流,从response直接获取,zip文件名称,前端设置 * @param fileList 需要压缩的文件集合 */ public static void downloadZipForFiles(OutputStream outputStream, List<File> fileList){ ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(outputStream); for (File file : fileList) {
//文件名最后会取new ZipEntity(String name)的name,可以在这里覆盖文件名 ZipEntry zipEntry = new ZipEntry(file.getName()); zipOutputStream.putNextEntry(zipEntry); byte[] buf = new byte[BUFFER_SIZE]; int len; FileInputStream in = new FileInputStream(file); while ((len = in.read(buf)) != -1) { zipOutputStream.write(buf, 0, len); zipOutputStream.flush(); } } zipOutputStream.flush(); zipOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭流 try { if (zipOutputStream != null ) { zipOutputStream.close(); } if (outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }