1.在Maven项目中加入依赖项
1 2 3 4 5
| <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.8.0</version> </dependency>
|
2.获取AccessKey
登录阿里云,在个人头像下面有一个AccessKey管理选项,点击进入创建一个AccessKey
3.创建一个Bucket
在阿里云的对象存储创建一个Bucket
4.编写上传类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| @Service public class AliyunProvider {
@Value("") private String AccessKeyID;
@Value("") private String AccessKeySecret;
public String upload(InputStream fileStream, String fileName){ String endpoint = ""; String accessKeyId = AccessKeyID; String accessKeySecret = AccessKeySecret; String bucketName = ""; String generatedFileName = ""; String[] filePaths = fileName.split("\\."); if (filePaths.length > 1){ generatedFileName = UUID.randomUUID().toString() + "." + filePaths[filePaths.length - 1]; }else { return null; }
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.createBucket(bucketName);
try { ossClient.putObject(bucketName, generatedFileName, fileStream); } catch (Exception e) { e.printStackTrace(); return null; }
ossClient.shutdown(); return generatedFileName; }
}
|
以上,就是阿里云OSS实现图片上传的流程