1.申請/購買OSS服務ide
在阿里雲上申請/購買OSS服務, 而後在會得AccessKeyID,AccessKeySecret,bucketName 這三個東西ui
2.增刪改查阿里雲
在pom.xml文件上增長url
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>
上傳/下載代碼spa
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 }
上傳完文件後,能夠經過如下鏈接進行訪問code
http://bucketName.oss-cn-shenzhen.aliyuncs.com/demo.txtorm
其中 bucketName 是須要本身申請的, 後面的demo.txt 文件名是在上傳文件是指定的keyxml
同時支持HTTPS對象
若是訪問的文件(Key)不存在blog
3.文件上傳/下載流程
對應到公司實際項目上