阿里云OSS官方文档:
快速使用OSS SDK_对象存储(OSS)-阿里云帮助中心 (aliyun.com)
在Maven工程中使用OSS Java SDK,只需在pom.xml中加入相应依赖即可。在<dependencies>中加入如下内容:
优先使用最新版本的依赖项,此处以3.15.1版本为例。
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.15.1</version> </dependency>
如果使用的是Java 9及以上的版本,则需要添加JAXB相关依赖。添加JAXB相关依赖示例代码如下:
<dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> <!-- no more than 2.3.3--> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.3</version> </dependency>
上传文件
以下代码用于通过流式上传的方式将文件上传到OSS。
代码运行成功后,exampledir
目录下将上传exampleobject.txt
文件。
1 import com.aliyun.oss.ClientException; 2 import com.aliyun.oss.OSS; 3 import com.aliyun.oss.OSSClientBuilder; 4 import com.aliyun.oss.OSSException; 5 import com.aliyun.oss.common.auth.CredentialsProviderFactory; 6 import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider; 7 import java.io.ByteArrayInputStream; 8 9 public class Demo { 10 11 public static void main(String[] args) throws Exception { 12 // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 13 String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; 14 // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 15 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); 16 // 填写Bucket名称,例如examplebucket。 17 String bucketName = "examplebucket"; 18 // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。 19 String objectName = "exampledir/exampleobject.txt"; 20 21 // 创建OSSClient实例。 22 OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider); 23 24 try { 25 String content = "Hello OSS"; 26 ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes())); 27 } catch (OSSException oe) { 28 System.out.println("Caught an OSSException, which means your request made it to OSS, " 29 + "but was rejected with an error response for some reason."); 30 System.out.println("Error Message:" + oe.getErrorMessage()); 31 System.out.println("Error Code:" + oe.getErrorCode()); 32 System.out.println("Request ID:" + oe.getRequestId()); 33 System.out.println("Host ID:" + oe.getHostId()); 34 } catch (ClientException ce) { 35 System.out.println("Caught an ClientException, which means the client encountered " 36 + "a serious internal problem while trying to communicate with OSS, " 37 + "such as not being able to access the network."); 38 System.out.println("Error Message:" + ce.getMessage()); 39 } finally { 40 if (ossClient != null) { 41 ossClient.shutdown(); 42 } 43 } 44 } 45 }标签:文件,存储,OSS,aliyun,println,com,oss,out From: https://www.cnblogs.com/linzepro/p/18231612