OSS SDK快速入门_对象存储(OSS)-阿里云帮助中心
阿里官方的SDK使用方法还得配置环境变量access Key、access Secret ,我没有配置,仅把access Key和access Secret写到了yml文件读取,结果上传图片时还是出现下面的问题。
[ ERROR ] [ com.serein.exception.GlobalExceptionHandler : 31 ] - RuntimeException
com.aliyun.oss.common.auth.InvalidCredentialsException: Access key id should not be null or empty.at com.aliyun.oss.common.auth.DefaultCredentialProvider.checkCredentials(DefaultCredentialProvider.java:63)at com.aliyun.oss.common.auth.DefaultCredentialProvider.<init>(DefaultCredentialProvider.java:38)at com.aliyun.oss.common.auth.DefaultCredentialProvider.<init>(DefaultCredentialProvider.java:34)at com.aliyun.oss.OSSClientBuilder.getDefaultCredentialProvider(OSSClientBuilder.java:83)at com.aliyun.oss.OSSClientBuilder.build(OSSClientBuilder.java:38
解决方法是把BUCKET_NAME、END_POINT 、ACCESS_KEY_ID 、ACCESS_KEY_SECRET直接写死到代码中,如下:
public static String uploadImageOSS(MultipartFile img) {OSS ossClient= new OSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);if (!ossClient.doesBucketExist(BUCKET_NAME)) {ossClient.createBucket(BUCKET_NAME);CreateBucketRequest createBucketRequest = new CreateBucketRequest(BUCKET_NAME);createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);ossClient.createBucket(createBucketRequest);}//filePath是存到oss的文件名,fileUrl是访问的路径String filePath = createOSSFileName(img.getOriginalFilename());PutObjectRequest putObjectRequest = null;try {putObjectRequest = new PutObjectRequest(BUCKET_NAME, filePath, img.getInputStream());} catch (IOException e) {throw new RuntimeException(e);}PutObjectResult result = ossClient.putObject(putObjectRequest);return "https://" + BUCKET_NAME + "." + END_POINT + "/" + filePath;}
然后再次上传图片就出现了下面的问题,因为前面填的是OSS内网oss-cn-beijing-internal.aliyuncs.com ,换成oss-cn-beijing.aliyuncs.com外网就ok了
[ WARN ] [ com.aliyun.oss : 70 ] - [Client]Unable to execute HTTP request:
Connect to xxxx.oss-cn-beijing-internal.aliyuncs.com:80
failed: Connection timed out: connect
[ErrorCode]: SocketException
[RequestId]: Unknown
然后图片成功上传到OSS了,但是外部并不能访问,如果拿着url在浏览器查看,会这样
<Error>
<Code>AccessDenied</Code>
<Message>You have no right to access this object because of bucket acl.</Message>
<RequestId>679391585E3414373911E999</RequestId>
<HostId>blog-backend.oss-cn-beijing.aliyuncs.com</HostId>
<EC>0003-00000001</EC>
<RecommendDoc>https://api.aliyun.com/troubleshoot?q=0003-00000001</RecommendDoc>
</Error>
解决方法就是关闭公共访问,并且设置读写权限为公共读,这样编辑器就可以根据url显示出图片了
成功渲染出图片!