POM

  1. <dependency>
  2. <groupId>com.aliyun.oss</groupId>
  3. <artifactId>aliyun-sdk-oss</artifactId>
  4. <version>3.8.0</version>
  5. </dependency>

Java

  1. public class UploadSample {
  2. private static String endpoint = "<endpoint, http://oss-cn-hangzhou.aliyuncs.com>";
  3. private static String accessKeyId = "<accessKeyId>";
  4. private static String accessKeySecret = "<accessKeySecret>";
  5. private static String bucketName = "<bucketName>";
  6. // 下载用的路径名
  7. private static String key = "<downloadKey>";
  8. private static String uploadFile = "<uploadFile>";
  9. public static void main(String[] args) throws IOException {
  10. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
  11. try {
  12. UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, key);
  13. // The local file to upload---it must exist.
  14. uploadFileRequest.setUploadFile(uploadFile);
  15. // Sets the concurrent upload task number to 5.
  16. uploadFileRequest.setTaskNum(5);
  17. // Sets the part size to 1MB.
  18. uploadFileRequest.setPartSize(1024 * 1024 * 1);
  19. // Enables the checkpoint file. By default it's off.
  20. uploadFileRequest.setEnableCheckpoint(true);
  21. UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
  22. CompleteMultipartUploadResult multipartUploadResult =
  23. uploadResult.getMultipartUploadResult();
  24. System.out.println(multipartUploadResult.getETag());
  25. } catch (OSSException oe) {
  26. System.out.println("Caught an OSSException, which means your request made it to OSS, "
  27. + "but was rejected with an error response for some reason.");
  28. System.out.println("Error Message: " + oe.getErrorMessage());
  29. System.out.println("Error Code: " + oe.getErrorCode());
  30. System.out.println("Request ID: " + oe.getRequestId());
  31. System.out.println("Host ID: " + oe.getHostId());
  32. } catch (ClientException ce) {
  33. System.out.println("Caught an ClientException, which means the client encountered "
  34. + "a serious internal problem while trying to communicate with OSS, "
  35. + "such as not being able to access the network.");
  36. System.out.println("Error Message: " + ce.getMessage());
  37. } catch (Throwable e) {
  38. e.printStackTrace();
  39. } finally {
  40. ossClient.shutdown();
  41. }
  42. }
  43. }

参考资料