POM
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
Java
public class UploadSample {
private static String endpoint = "<endpoint, http://oss-cn-hangzhou.aliyuncs.com>";
private static String accessKeyId = "<accessKeyId>";
private static String accessKeySecret = "<accessKeySecret>";
private static String bucketName = "<bucketName>";
// 下载用的路径名
private static String key = "<downloadKey>";
private static String uploadFile = "<uploadFile>";
public static void main(String[] args) throws IOException {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, key);
// The local file to upload---it must exist.
uploadFileRequest.setUploadFile(uploadFile);
// Sets the concurrent upload task number to 5.
uploadFileRequest.setTaskNum(5);
// Sets the part size to 1MB.
uploadFileRequest.setPartSize(1024 * 1024 * 1);
// Enables the checkpoint file. By default it's off.
uploadFileRequest.setEnableCheckpoint(true);
UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
CompleteMultipartUploadResult multipartUploadResult =
uploadResult.getMultipartUploadResult();
System.out.println(multipartUploadResult.getETag());
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message: " + oe.getErrorMessage());
System.out.println("Error Code: " + oe.getErrorCode());
System.out.println("Request ID: " + oe.getRequestId());
System.out.println("Host ID: " + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ce.getMessage());
} catch (Throwable e) {
e.printStackTrace();
} finally {
ossClient.shutdown();
}
}
}
参考资料