日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

JAVA后台实现文件批量下载

發(fā)布時(shí)間:2023/12/18 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JAVA后台实现文件批量下载 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

工具類:

/*** 本地文件路徑*/private static final String FILE_PATH = "F:\\test"; /*** 批量下載文件** @param list 批量文件集合(前端只傳id集合,后端去查數(shù)據(jù)庫拿到文件信息)* @param request request* @param response response* @param <T> 實(shí)體類 extends BaseEntityPoJo */public static <T extends BaseEntityPoJo> void batchDownloadFile(List<T> list, HttpServletRequest request, HttpServletResponse response) {//設(shè)置響應(yīng)頭信息response.reset();response.setCharacterEncoding("utf-8");response.setContentType("multipart/form-data");//設(shè)置壓縮包的名字,date為時(shí)間戳String date = DateUtil.formatDateTimeSecond(new Date());String downloadName = "壓縮包" + date + ".zip";//返回客戶端瀏覽器的版本號(hào)、類型String agent = request.getHeader("USER-AGENT");try {//針對(duì)IE或者以IE為內(nèi)核的瀏覽器: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 + "\"");//設(shè)置壓縮流:直接寫入response,實(shí)現(xiàn)邊壓縮邊下載ZipOutputStream zipOs = null;//循環(huán)將文件寫入壓縮流DataOutputStream os = null;//文件File file;try {zipOs = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));//設(shè)置壓縮方法zipOs.setMethod(ZipOutputStream.DEFLATED);//遍歷文件信息(主要獲取文件名/文件路徑等)for (T t : list) {try {//文件名(包含后綴名,如:測(cè)試.pdf)Field field = t.getClass().getDeclaredField("name");field.setAccessible(true);String name = field.get(t).toString();//本地文件路徑(絕對(duì)路徑,包含后綴名,如:F:\\test\\測(cè)試.pdf),這里是在windows上測(cè)試的,路徑是反斜杠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;//讀入需要下載的文件的內(nèi)容,打包到zip文件while ((length = fs.read(b)) != -1) {os.write(b, 0, length);}//關(guān)閉流fs.close();zipOs.closeEntry();//==============此處如果是網(wǎng)絡(luò)文件路徑,可按如下方式讀取=============/*//文件名(包含后綴名,如:測(cè)試.pdf)Field field = t.getClass().getDeclaredField("name");field.setAccessible(true);String name = field.get(t).toString() + ".pdf";//網(wǎng)絡(luò)文件路徑(瀏覽器可直接訪問的路徑,如:http://192.168.0.12/frame-service-gengbao/document/四川省2022第四季度報(bào)告.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;//讀入需要下載的文件的內(nèi)容,打包到zip文件while ((length = is.read(b)) != -1) {os.write(b, 0, length);}is.close();zipOs.closeEntry();*/} catch (IllegalAccessException | NoSuchFieldException e) {log.error("下載文件出錯(cuò)![{}]", e.getMessage());}}} catch (Exception e) {e.printStackTrace();} finally {//關(guān)閉流try {if (os != null) {os.flush();os.close();}if (zipOs != null) {zipOs.close();}} catch (IOException e) {e.printStackTrace();}}}

控制層:

/*** 批量下載(測(cè)試時(shí)可改為GET請(qǐng)求,瀏覽器直接調(diào)用接口)** @param ids 用于查詢相關(guān)表獲取文件信息* @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);}

上面用到的方法
分割字符串:

public static List<Integer> splitToLong(final String str) {return StringUtils.isEmpty(str) ? Collections.emptyList() : Stream.of(str.split(",")).map(Integer::valueOf).collect(Collectors.toList());}

獲取時(shí)間戳:

/*** 將日期解析成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);}

注意:我這里為了對(duì)各種文件通用下載,工具類用的泛型方法,如果不需要泛型的,直接傳入自己需要的實(shí)體類集合就可以了。

測(cè)試接口:

總結(jié)

以上是生活随笔為你收集整理的JAVA后台实现文件批量下载的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。