阿里雲OSS的購買和使用可以參考我的這篇博客:阿里雲OSS存儲的購買和使用
1、導入相關依賴
<!--阿里雲OSS依賴--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.9.1</version> </dependency> <!--日期處理依賴--> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.1</version> </dependency>
2、創建相關配置類
@Configuration @PropertySource("classpath:aliyun.yaml") //讀取配置文件 @ConfigurationProperties(prefix = "aliyun") @Data public class AliyunConfig { private String endpoint ; private String accessKeyId; private String accessKeySecret; @Bean public OSS ossClient(){ return new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret); } }
這里需要注意的是endpoint,accessKeyId,accessKeySecret的值是寫到了配置文件中,使用@PropertySource注解來讀取配置文件
配置文件我這里使用的是yaml格式,看起來層次更加清晰
同時還需要使用@ConfigurationProperties(prefix = "aliyun")注解來指定哪個前綴下面的值會被注入到AliyunConfig類的屬性中(需要注意的是,該注解注入屬性的方式是使用set方法,所以必須為AliyunConfig類中的屬性提供set方法,我這里使用了@Data注解來簡化開發)
@ConfigurationProperties注解使用的時候需要添加下面的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
配置文件中的endpoint指的是域名節點,可以在你創建的bucket概覽中查看
accessKeyId和accessKeySecret的獲取
1、鼠標放在登錄頭向上,點擊AccessKey管理
2、點擊使用子用戶
3、創建用戶
4、創建成功之后點擊用戶
5、點擊創建AccessKey
6、將創建好的信息保存(accessSecret只能通過改方法獲取一次,彈框關閉之后再也無法查看了!!!)
編寫上傳邏輯代碼
1、自定義結果類
@Data public class PicUploadResult { /* * 這個類是我自定義的結果類,不一定非要按照這個格式寫,里面的屬性都可以自己定義 * */ private String uid; //自定義ID private String name;//自定義文件名稱 private String status;//上傳結果的狀態 private String response;//上傳響應的狀態 public PicUploadResult() { } public PicUploadResult(String uid, String name, String status, String response) { this.uid = uid; this.name = name; this.status = status; this.response = response; } }
2、controller
@Controller @CrossOrigin //我使用的是前后端分離,該注解用來解決跨域問題 @RequestMapping("/picUpload") public class PicUploadController { @Autowired private PicUploadService picUploadService; @PostMapping() @ResponseBody public PicUploadResult upload(@RequestParam("file")MultipartFile file){ return picUploadService.upload(file); } }
3、service層(主要邏輯代碼的書寫位置)
@Service public class PicUploadServiceImpl implements PicUploadService { //注入OSS對象 @Autowired private OSS oss; @Autowired private AliyunConfig aliyunConfig; //允許上傳的格式 private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".webp", ".gif", ".png"}; @Override public PicUploadResult upload(MultipartFile file) { PicUploadResult result = new PicUploadResult(); //對圖片的后綴名做校驗 boolean isLegal = false; for (String type : IMAGE_TYPE) { if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) { isLegal = true; break; } } if (!isLegal) { result.setStatus("error"); return result; } //設置文件的路徑,getFilePath為封裝的自定義路徑的方法,在下面 String fileName = file.getOriginalFilename(); String filePath = getFilePath(fileName); //上傳到阿里雲 try { //調用阿里雲提供的API oss.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(file.getBytes())); } catch (IOException e) { e.printStackTrace(); result.setStatus("error"); return result; } result.setStatus("success"); result.setName(aliyunConfig.getUrlPrefix() + fileName); result.setUid(String.valueOf(System.currentTimeMillis())); System.out.println("result = " + result); return result; } //定義生成文件新路徑的方法,目錄結構:images+年+月+日+xxx.jpg private String getFilePath(String sourceFileName) { DateTime dateTime = new DateTime(); return "images" + "/" + dateTime.toString("yyyy") + "/" + dateTime.toString("MM") + "/" + dateTime.toString("dd") + "/" + System.currentTimeMillis() + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, "."); } }
邏輯已經寫完了,大家自行測試吧!!!
------------------------------------------------------------------------------------------------------------------------------我是分割線-----------------------------------------------------------------------------------------------------------------------------------------------
把我在實現文件上傳時候遇到的坑寫出來給大家作參考,避免踩坑
錯誤一:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'picUploadController':
Unsatisfied dependency expressed through field 'picUploadService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'picUploadServiceImpl': Unsatisfied dependency expressed through field 'oss';
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'oss' defined in class path resource [com/jingzhe/blog/config/AliyunConfig.class]:
Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate
[com.aliyun.oss.OSS]: Factory method 'oss' threw exception; nested exception is
java.lang.IllegalArgumentException: java.net.URISyntaxException: Illegal character in authority at index 7: http://oss-cn-beijing.aliyuncs.com
這個錯誤真的是讓我懵逼了很長時間,我一直以為是配置類出現了問題,但是翻來覆去的檢查都覺得我寫的是ok的(事實證明的確是OK的)
為了解決它我瘋狂的百度、翻資料,本來就少的頭發更是刷刷的往下掉,后來無意間(真的是,緣分這東西太™奇妙了)找到一篇帖子,說的是配置文件中的url路徑可能寫錯了
嗯?!??!!!!0_0.。。。
在我一個字母一個字母翻來覆去的對比之后,終於發現了!!!!!一個不起眼的空格。。。。
就是他!!!!去掉空格之后,項目成功運行,所以說,大家在遇到錯誤的時候一定不能心急,仔細一些,有些錯誤很可能自己就蹦出來了
------------------------------------
錯誤2:You have no right to access this object because of bucket acl.
這個錯誤是在測試的時候出現的問題,原因是你所使用的子用戶沒有被授權。
添加完成在測試就OK了。至此,文件上傳至阿里雲告一段落。
祝大家處事不驚,前程似錦,晚安!