JAVA后台实现文件批量下载
生活随笔
收集整理的這篇文章主要介紹了
JAVA后台实现文件批量下载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
工具類:
/*** 本地文件路徑*/private static final String FILE_PATH = "F:\\test"; /*** 批量下載文件** @param list 批量文件集合(前端只傳id集合,后端去查數據庫拿到文件信息)* @param request request* @param response response* @param <T> 實體類 extends BaseEntityPoJo */public static <T extends BaseEntityPoJo> void batchDownloadFile(List<T> list, HttpServletRequest request, HttpServletResponse response) {//設置響應頭信息response.reset();response.setCharacterEncoding("utf-8");response.setContentType("multipart/form-data");//設置壓縮包的名字,date為時間戳String date = DateUtil.formatDateTimeSecond(new Date());String downloadName = "壓縮包" + date + ".zip";//返回客戶端瀏覽器的版本號、類型String agent = request.getHeader("USER-AGENT");try {//針對IE或者以IE為內核的瀏覽器:if (agent.contains("MSIE") || agent.contains("Trident")) {downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");} else {//非IE瀏覽器的處理:downloadName = new String(downloadName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);}} catch (Exception e) {e.printStackTrace();}response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");//設置壓縮流:直接寫入response,實現邊壓縮邊下載ZipOutputStream zipOs = null;//循環將文件寫入壓縮流DataOutputStream os = null;//文件File file;try {zipOs = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));//設置壓縮方法zipOs.setMethod(ZipOutputStream.DEFLATED);//遍歷文件信息(主要獲取文件名/文件路徑等)for (T t : list) {try {//文件名(包含后綴名,如:測試.pdf)Field field = t.getClass().getDeclaredField("name");field.setAccessible(true);String name = field.get(t).toString();//本地文件路徑(絕對路徑,包含后綴名,如:F:\\test\\測試.pdf),這里是在windows上測試的,路徑是反斜杠String path = FILE_PATH + File.separator + name;log.info("batchDownloadFile:[filePath:{}]", path);file = new File(path);if (!file.exists()) {throw new RuntimeException("文件不存在");}//添加ZipEntry,并將ZipEntry寫入文件流zipOs.putNextEntry(new ZipEntry(name));os = new DataOutputStream(zipOs);FileInputStream fs = new FileInputStream(file);byte[] b = new byte[100];int length;//讀入需要下載的文件的內容,打包到zip文件while ((length = fs.read(b)) != -1) {os.write(b, 0, length);}//關閉流fs.close();zipOs.closeEntry();//==============此處如果是網絡文件路徑,可按如下方式讀取=============/*//文件名(包含后綴名,如:測試.pdf)Field field = t.getClass().getDeclaredField("name");field.setAccessible(true);String name = field.get(t).toString() + ".pdf";//網絡文件路徑(瀏覽器可直接訪問的路徑,如:http://192.168.0.12/frame-service-gengbao/document/四川省2022第四季度報告.pdf)Field urlField = t.getClass().getDeclaredField("url");urlField.setAccessible(true);URL url = new URL(urlField.get(t).toString());URLConnection connection = url.openConnection();InputStream is = connection.getInputStream();//添加ZipEntry,并將ZipEntry寫入文件流zipOs.putNextEntry(new ZipEntry(name));os = new DataOutputStream(zipOs);byte[] b = new byte[100];int length;//讀入需要下載的文件的內容,打包到zip文件while ((length = is.read(b)) != -1) {os.write(b, 0, length);}is.close();zipOs.closeEntry();*/} catch (IllegalAccessException | NoSuchFieldException e) {log.error("下載文件出錯![{}]", e.getMessage());}}} catch (Exception e) {e.printStackTrace();} finally {//關閉流try {if (os != null) {os.flush();os.close();}if (zipOs != null) {zipOs.close();}} catch (IOException e) {e.printStackTrace();}}}控制層:
/*** 批量下載(測試時可改為GET請求,瀏覽器直接調用接口)** @param ids 用于查詢相關表獲取文件信息* @param request request* @param response response*/@GetMapping("/batchDownloadFile")@ApiOperation("批量下載")public void batchDownloadFile(@RequestParam("ids") final String ids,HttpServletRequest request,HttpServletResponse response) {log.info("downloadPlanFile:批量下載[ids:{},request:{},response:{}]", ids, request, response);List<Integer> idList = ControllerHelper.splitToLong(ids);List<RegulatoryReport> list = service.list(idList);FileUtil.batchDownloadFile(list, request, response);}上面用到的方法
分割字符串:
獲取時間戳:
/*** 將日期解析成yyyyMMddHHmmss的字符串** @param date the date* @return the string*/public static String formatDateTimeSecond(Date date) {if (date == null) {return "";}return new SimpleDateFormat(DATETIME_STAMP_SECOND, Locale.CHINA).format(date);}注意:我這里為了對各種文件通用下載,工具類用的泛型方法,如果不需要泛型的,直接傳入自己需要的實體類集合就可以了。
測試接口:
總結
以上是生活随笔為你收集整理的JAVA后台实现文件批量下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为手机禁用省电精灵
- 下一篇: GO 大写金额转换