- Amazon S3会限制单次上传的大小,上传过大的文件会导致上传失败(单次上传的最大数据元是5GB),官方建议的是大于100MB的文件就应该考虑分段上传。
一般而言,如果您的对象大小达到了 100 MB,您应该考虑使用分段上传,而不是在单个操作中上传对象。
官方文档地址
网上的代码大部分要么是单线程执行很慢,要么就是本地的临时文件(File)没有删除,这里参考了网上现有的代码做了一些整合,具体代码如下:
public void uploadMultipartFileByPart(MultipartFile file, String s3Key) {
AmazonS3 s3;
String bucketName = "bucketName";
ExecutorService exec = Executors.newFixedThreadPool(3);
long size = file.getSize();
int minPartSize = 5 * 1024 * 1024;
List<Long> positions = new ArrayList<>();
long filePosition = 0;
while (filePosition < size) {
positions.add(filePosition);
filePosition += Math.min(minPartSize, (size - filePosition));
}
log.info("总大小:{},分为{}段", size, positions.size());
List<PartETag> partETags = new ArrayList<>();
InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, s3Key);
InitiateMultipartUploadResult initResponse = s3.initiateMultipartUpload(initRequest);
log.info("开始上传");
long begin = System.currentTimeMillis();
try {
File toFile = multipartFileToFile(file);
for (int i = 0; i < positions.size(); i++) {
int finalI = i;
exec.execute(() -> {
long time1 = System.currentTimeMillis();
UploadPartRequest uploadRequest = new UploadPartRequest()
.withBucketName(bucketName)
.withKey(s3Key)
.withUploadId(initResponse.getUploadId())
.withPartNumber(finalI + 1)
.withFileOffset(positions.get(finalI))
.withFile(toFile)
.withPartSize(Math.min(minPartSize, (size - positions.get(finalI))));
partETags.add(s3.uploadPart(uploadRequest).getPartETag());
long time2 = System.currentTimeMillis();
log.info("第{}段上传耗时:{}", finalI + 1, (time2 - time1));
});
}
exec.shutdown();
while (true) {
if (exec.isTerminated()) {
break;
}
}
CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(bucketName, s3Key,
initResponse.getUploadId(), partETags);
s3.completeMultipartUpload(compRequest);
toFile.delete();
} catch (Exception e) {
s3.abortMultipartUpload(new AbortMultipartUploadRequest(bucketName, s3Key, initResponse.getUploadId()));
log.error("Failed to upload, " + e.getMessage());
}
long end = System.currentTimeMillis();
log.info("总上传耗时:{}", (end - begin));
}
public static File multipartFileToFile(MultipartFile file) throws Exception {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
OutputStream os = new FileOutputStream(toFile);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
}
return toFile;
}
|