上传zip包方法
public static List<String> uploadZipMultiFile(MultipartFile fileData) {
List<String> urls = new ArrayList<>();
ZipInputStream zip = new ZipInputStream(fileData.getInputStream(), Charset.forName("UTF-8"));
ZipEntry fileEntry;
String env = "resource/";
while ((fileEntry = zip.getNextEntry()) != null) {
if (!fileEntry.isDirectory()) {
String filename = fileEntry.getName();
String suffix = StringUtils.substringAfterLast(filename, ".");
filename = env + filename;
@Cleanup ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
byte[] byte_s=new byte[1024];
int num;
while((num=zip.read(byte_s,0,byte_s.length))>-1) {//通过read方法来读取文件内容
byteArrayOutputStream.write(byte_s, 0, num);
}
byte[] byte_s_=byteArrayOutputStream.toByteArray();
String md5 = DigestUtils.md5Hex(byte_s_);
createFolder(env);
uploadFile(filename,byte_s_);
filename= filename+"?md5="+md5;
if (StringUtils.contains(contentType(suffix), "image")) {
urls.add(OSS_IMAGE_HOST + filename);
} else {
urls.add( OSS_HOST + filename);
}
}
}
zip.close();
return urls;
}
/**
* @param key
* @param content 文件内容
* @throws Exception
*/
private static void uploadFile(String key, byte[] content) throws Exception {
ObjectMetadata objectMeta = new ObjectMetadata();
objectMeta.setContentLength(content.length);
@Cleanup InputStream input = new ByteArrayInputStream(content);
client.putObject(OSS_BUCKET, key, input, objectMeta);
}
/**
* 创建目录
*
* @param path 目录结构,这个有要求必须是 "xxx/xxx/" 以目录名开头,/结尾
* @throws IOException
*/
private static void createFolder(String path) throws IOException {
if (folderCache.containsKey(path)) return;
ObjectMetadata objectMeta = new ObjectMetadata();
byte[] buffer = new byte[0];
objectMeta.setContentLength(0);
try (ByteArrayInputStream in = new ByteArrayInputStream(buffer)) {
client.putObject(OSS_BUCKET, path, in, objectMeta);
}
folderCache.put(path, true);
}