1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| String username = SecurityUtils.getUsername(); String regex = ".*[\\u4e00-\\u9fa5]+.*";
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); List<Future<?>> futures = new ArrayList<>(); InputStream inputStream = file.getInputStream(); try (ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(inputStream)) { ZipArchiveEntry entry; while ((entry = zipInputStream.getNextZipEntry()) != null) { if (!entry.isDirectory()) { String zipEntryName = entry.getName(); if (zipEntryName.matches(regex)) { throw new Exception("压缩文件中不能包含中文名"); } String key = StringUtils.isNotEmpty(folderName) ? folderName + "/" + zipEntryName.replaceAll(" ", "_") : zipEntryName.replaceAll(" ", "_");
File tempFile = File.createTempFile("upload_", "_" + zipEntryName.replaceAll("[\\\\/]", "_")); try (OutputStream out = new FileOutputStream(tempFile)) { byte[] buffer = new byte[8192]; int len; while ((len = zipInputStream.read(buffer)) != -1) { out.write(buffer, 0, len); } } ZipArchiveEntry finalEntry = entry; futures.add(executor.submit(() -> { try (InputStream uploadStream = new FileInputStream(tempFile)) { ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentType(getContentType(finalEntry.getName())); objectMetadata.addUserMetadata("uploader", username); objectMetadata.setContentLength(tempFile.length()); initiateMultipartUpload2(key, uploadStream, objectMetadata); } catch (Exception e) { throw new RuntimeException("上传文件 " + key + " 失败", e); } finally { if (!tempFile.delete()) { System.err.println("临时文件删除失败:" + tempFile.getAbsolutePath()); } } })); } } } finally { inputStream.close(); }
for (Future<?> future : futures) { future.get(); } executor.shutdown();
|