Java純代碼實現(xiàn)導(dǎo)出文件為壓縮包
今天做需求突然看到之前產(chǎn)品提的需求,導(dǎo)出多個文件為壓縮包。功能部分早就已經(jīng)完成了,想到還沒有過類似的記錄,今天就記錄下來吧,是記錄也是學(xué)歷,如果有不對的地方還請多多指教。以下貼出的代碼是下載壓縮包的源代碼,我的文件資源是存儲在服務(wù)器根目錄下,表中記錄的文件存儲的絕對路徑,通過路徑反查獲取資源下載,看官可根據(jù)自己項目的情況判斷是否適用你當(dāng)下的需求場景。廢話不多說,直接上代碼:
controller層:
/** * 下載壓縮包 * @param request * @param response * @param idDTO 傳入文件id */ @SneakyThrows @PostMapping("/download-zip") @ApiOperation(value = "下載文件為壓縮包") public SwaggerAjaxResult downloadFileZip(HttpServletRequest request, HttpServletResponse response, @RequestBody @Valid UpdateFileDTO idDTO){ return SwaggerAjaxResult.success(inspectionProblemService.downloadFileZip(request,response,idDTO.getId())); }
service 層代碼:
/** * 下載文件為壓縮包 * * @param request * @param response * @param id */ @Override @Transactional(rollbackFor = Exception.class) public SwaggerAjaxResult downloadFileZip(HttpServletRequest request, HttpServletResponse response, String id) { try { List<TFile> fileVOList = fileService.lambdaQuery() .eq(TFile::getParentId, id) .eq(TFile::getParentTable, PROBLEM_TABLE_NAME) .eq(TFile::getType, WJXX) .list(); Assert.notNull(fileVOList, "文件為空!"); String fileName = super.baseMapper.getFileName(id); Assert.notNull(fileName, "文件名不能為空!"); //創(chuàng)建臨時路徑,存放壓縮文件 String zipFilePath = System.getProperty("user.dir") + File.separator + "downloadZip" + File.separator; log.info("文件臨時路徑為:{}", zipFilePath); //如果文件不存在創(chuàng)創(chuàng)建新文件 File zipFile = new File(zipFilePath); if (!zipFile.exists()) { zipFile.mkdirs(); } //在臨時文件夾里創(chuàng)建臨時文件 String temporaryZipName = zipFilePath + "臨時存放.zip"; //如果不存在就新創(chuàng)建一個 File zipFiles = new File(temporaryZipName); if (!zipFiles.exists()) { zipFiles.createNewFile(); } //壓縮輸出流,將臨時文件輸出流包裝成壓縮流,將所有文件輸出到這里,打成zip包 ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(temporaryZipName)); //將文件寫入壓縮包 for (TFile file : fileVOList) { writingFilesToZip(zipFilePath, zipOut, file, request); } //壓縮完成關(guān)閉壓縮流 zipOut.close(); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".zip"); response.setCharacterEncoding("UTF-8"); response.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); ServletOutputStream outputStream = response.getOutputStream(); FileInputStream inputStream = new FileInputStream(temporaryZipName); IOUtils.copy(inputStream, outputStream); //關(guān)閉輸入流 inputStream.close(); //下載完成,刪除臨時文件 File file = new File(zipFilePath); FileUtils.deleteFile(file); log.info("下載zip成功!"); return SwaggerAjaxResult.success("下載zip成功!"); } catch (IOException e) { e.printStackTrace(); log.warn("下載zip失敗!{}", e.getMessage()); return SwaggerAjaxResult.error("下載zip失敗!{}", e.getMessage()); } }
/** * @param zipFilePath * @param zipOut * @param fileVO */ private void writingFilesToZip(String zipFilePath, ZipOutputStream zipOut, TFile fileVO, HttpServletRequest request) throws IOException { String savePath = fileVO.getFileLink(); //通過URL將文件下載至本地 downLoadFromUrl(savePath, zipFilePath, fileVO.getFileName(), request); byte[] buf = new byte[2 * 1024]; String srcDir = zipFilePath + fileVO.getFileName(); File sourceFile = new File(srcDir); zipOut.putNextEntry(new ZipEntry(fileVO.getFileName())); int len; FileInputStream in = new FileInputStream(sourceFile); while ((len = in.read(buf)) != -1) { zipOut.write(buf, 0, len); } zipOut.closeEntry(); in.close(); }
private void downLoadFromUrl(String savePath, String zipFilePath, String fileName, HttpServletRequest request) throws IOException { File file1 = new File(savePath); byte[] getData = new byte[0]; try { getData = org.apache.commons.io.FileUtils.readFileToByteArray(file1); } catch (IOException e) { log.warn("文件:{}不能訪問!", savePath); } //文件保存位置 File saveDir = new File(zipFilePath); if (!saveDir.exists()) { saveDir.mkdir(); } File file = new File(saveDir + File.separator + fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); fos.close(); }
如有不足,請多多指教!
以上就是Java純代碼實現(xiàn)導(dǎo)出文件為壓縮包的詳細內(nèi)容,更多關(guān)于Java導(dǎo)出文件為壓縮包的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用Jenkins自動化構(gòu)建工具進行敏捷開發(fā)
這篇文章主要為大家介紹了使用Jenkins自動化構(gòu)建工具進行敏捷開發(fā),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪2022-04-04shrio中hashedCredentialsMatcher密碼匹配示例詳解
shrio是一個輕量級權(quán)限管理框架,密碼的匹配由框架內(nèi)部完成。密碼是否匹配由接口CredentialsMatcher定義實現(xiàn)類完成,CredentialsMatcher實現(xiàn)類有SimpleCredentialsMatcher和HashedCredentialsMatcher兩個2021-10-10PowerJob的GridFsManager工作流程源碼解讀
這篇文章主要為大家介紹了PowerJob的GridFsManager工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01SpringCloud?Function?SpEL注入漏洞分析及環(huán)境搭建
SpringCloud 是一套分布式系統(tǒng)的解決方案,常見的還有阿里巴巴的Dubbo,F(xiàn)ass的底層實現(xiàn)就是函數(shù)式編程,SpringCloud Function 就是Spring提供的分布式函數(shù)式編程組件,下面給大家介紹下SpringCloud?Function?SpEL注入漏洞分析,感興趣的朋友一起看看吧2022-04-04SpringBoot的Security和OAuth2的使用示例小結(jié)
這篇文章主要介紹了SpringBoot的Security和OAuth2的使用,本文通過示例圖文相結(jié)合給大家講解的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-06-06SpringBoot使用Sa-Token實現(xiàn)賬號封禁、分類封禁、階梯封禁的示例代碼
本文主要介紹了SpringBoot使用Sa-Token實現(xiàn)賬號封禁、分類封禁、階梯封禁的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07