java 大文件上传oss
时间: 2023-11-21 12:55:24 浏览: 103
java大文件上传
5星 · 资源好评率100%
以下是Java实现上传大文件到OSS的步骤和代码示例:
1. 引入OSS SDK依赖
在Maven项目中,可以在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
```
2. 初始化OSSClient
```java
String endpoint = "yourEndpoint";
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
String bucketName = "yourBucketName";
// 创建OSSClient实例
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 判断Bucket是否存在,不存在则创建
if (!ossClient.doesBucketExist(bucketName)) {
ossClient.createBucket(bucketName);
}
```
3. 分片上传文件
```java
String objectName = "yourObjectName"; // 上传到OSS的文件名
String filePath = "yourFilePath"; // 本地文件路径
// 初始化分片上传
InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName);
InitiateMultipartUploadResult result = ossClient.initiateMultipartUpload(request);
String uploadId = result.getUploadId();
// 设置分片大小
final long partSize = 1024 * 1024 * 1; // 1MB
// 计算分片数目
File file = new File(filePath);
long fileLength = file.length();
int partCount = (int) (fileLength / partSize);
if (fileLength % partSize != 0) {
partCount++;
}
// 上传分片
List<PartETag> partETags = new ArrayList<>();
for (int i = 0; i < partCount; i++) {
long startPos = i * partSize;
long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
FileInputStream fis = new FileInputStream(file);
fis.skip(startPos);
UploadPartRequest uploadPartRequest = new UploadPartRequest();
uploadPartRequest.setBucketName(bucketName);
uploadPartRequest.setKey(objectName);
uploadPartRequest.setUploadId(uploadId);
uploadPartRequest.setInputStream(fis);
uploadPartRequest.setPartSize(curPartSize);
uploadPartRequest.setPartNumber(i + 1);
UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
partETags.add(uploadPartResult.getPartETag());
fis.close();
}
// 完成分片上传
CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
ossClient.completeMultipartUpload(completeMultipartUploadRequest);
```
4. 关闭OSSClient
```java
ossClient.shutdown();
```
阅读全文