private static final String OSS_ENDPOINT = PropertiesUtil.getString("oss.endpoint"); private static final String OSS_ACCESS_KEY = PropertiesUtil.getString("oss.access.key"); private static final String OSS_SECRET = PropertiesUtil.getString("oss.secret"); private static final String OSS_BUCKET_NAME = PropertiesUtil.getString("oss.bucket.name"); // private static final String OSS_CT_BUCKET_NAME = // PropertiesUtil.getString("oss.bucket.ct.name"); private static final OSSClient OSS_CLIENT = new OSSClient(OSS_ENDPOINT, OSS_ACCESS_KEY, OSS_SECRET); /** * 批量下載oss 文件 並打成zip 包 返回到response中 * * @param fileNames * oss上的文件名集合 如:product/image/3448275920.png * @param zipFileName * 壓縮包文件名 * @param response * HttpServletResponse */ public static void batchDownLoadOssFile(List<String> fileNames, String zipFileName, HttpServletResponse response) { response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); //要下載成什么類型的文件,這里直接加后綴 response.setHeader("Content-Disposition", "attachment;fileName=" + zipFileName + ".zip"); BufferedInputStream bis = null; try { ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); for (String fileName : fileNames) { Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(OSS_BUCKET_NAME, fileName, HttpMethod.GET); // 設置過期時間。 request.setExpiration(expiration); // request.setContentType("application/pdf"); // 生成簽名URL(HTTP GET請求)。 URL signedUrl = OSS_CLIENT.generatePresignedUrl(request); // 使用簽名URL發送請求。 OSSObject ossObject = OSS_CLIENT.getObject(signedUrl, new HashMap<>()); if (ossObject != null) { InputStream inputStream = ossObject.getObjectContent(); byte[] buffs = new byte[1024 * 10]; String zipFile = fileName.substring(fileName.lastIndexOf("/") + 1)+".pdf"; ZipEntry zipEntry = new ZipEntry(zipFile); zos.putNextEntry(zipEntry); bis = new BufferedInputStream(inputStream, 1024 * 10); int read; while ((read = bis.read(buffs, 0, 1024 * 10)) != -1) { zos.write(buffs, 0, read); } ossObject.close(); } } zos.close(); //關閉流 IOUtil.close(bis); } catch (Exception e) { LOGGER.error("打包下載發生異常:",e); } finally { // 關閉流 try { response.getOutputStream().flush(); response.getOutputStream().close(); } catch (IOException e) { e.printStackTrace(); } } }
springboot框架,前端加一個接口
@GetMapping(value = "/downloadBookZip") public void downloadBookZip(HttpServletRequest request,HttpServletResponse response) { String subjectIdstr = request.getParameter("subjectId"); String className = request.getParameter("className"); String studentNum = request.getParameter("studentNum"); if(Strings.isNullOrEmpty(subjectIdstr)) { throw new BusinessException(BusinessExceptionEnum.PARAM_ERROR, "必須有科目ID"); } Long subjectId = Long.parseLong(subjectIdstr); //查詢生成文件路徑 List<String> list = wrongTopicDao.queryWrongTopicOssKey(subjectId,className,studentNum);
//上面按照個人業務查詢自己的文件key即可 OssUtil.batchDownLoadOssFile(list, "books", response); }