阿里云oss service代码
时间: 2024-06-09 07:04:33 浏览: 145
阿里云oss web上传demo.rar
以下是使用Java SDK操作阿里云OSS的示例代码:
```java
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import java.io.File;
import java.io.InputStream;
import java.util.List;
public class AliyunOSSExample {
private static final String accessKeyId = "your_access_key_id";
private static final String accessKeySecret = "your_access_key_secret";
private static final String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
private static final String bucketName = "your_bucket_name";
public static void main(String[] args) {
// 创建OSSClient实例
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 列举所有的Bucket
List<Bucket> bucketList = ossClient.listBuckets();
for (Bucket bucket : bucketList) {
System.out.println(bucket.getName());
}
// 上传文件
String objectName = "example.txt";
InputStream inputStream = AliyunOSSExample.class.getResourceAsStream("/example.txt");
PutObjectResult result = ossClient.putObject(bucketName, objectName, inputStream);
System.out.println(result.getETag());
// 下载文件
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
InputStream content = ossObject.getObjectContent();
// do something with content
// 列举指定Bucket下的所有文件
ObjectListing objectListing = ossClient.listObjects(bucketName);
List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
for (OSSObjectSummary objectSummary : objectSummaries) {
System.out.println(objectSummary.getKey());
}
// 删除文件
ossClient.deleteObject(bucketName, objectName);
// 关闭OSSClient实例
ossClient.shutdown();
}
}
```
在上述代码中,我们通过accessKeyId和accessKeySecret来进行身份验证,然后通过endpoint指定OSS的访问地址,bucketName指定Bucket的名称。接着,我们通过OSSClient实例可以进行Bucket的列举、文件上传、下载、文件列表查询、文件删除等操作。最后需要调用shutdown()方法来关闭OSSClient实例。
阅读全文