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