1.申请/购买OSS服务
在阿里云上申请/购买OSS服务, 然后在会得AccessKeyID,AccessKeySecret,bucketName 这三个东西
2.增删改查
在pom.xml文件上增加
<!-- https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.0.0</version>
</dependency>
上传/下载代码
public class OSSUploadFile {
public static String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
public static String accessKeyId = "L*****************";
public static String accessKeySecret = "4********************c";
public static String bucketName = "io****e"; /**
* 上传文件到阿里云OSS
* @param file 本地文件对象
* @param key oss对于url
* @return
*/
public static boolean uploadFile(File file, String key) {
OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
client.putObject(new PutObjectRequest(bucketName, key, file));
client.setObjectAcl(bucketName, key, CannedAccessControlList.PublicRead);
client.setObjectAcl(bucketName, key, CannedAccessControlList.Default);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 删除阿里云OSS上文件
* @param key
* @return
*/
public static boolean deleteFile(String key) {
try {
OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
boolean exists = client.doesObjectExist(bucketName, key);
if(exists) {
client.deleteObject(bucketName, key);
}
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
上传完文件后,可以通过以下连接进行访问
http://bucketName.oss-cn-shenzhen.aliyuncs.com/demo.txt
其中 bucketName 是需要自己申请的, 后面的demo.txt 文件名是在上传文件是指定的key
同时支持HTTPS
如果访问的文件(Key)不存在
3.文件上传/下载流程
对应到公司实际项目上