阿里云的文件OSS文件存储对象
在阿里云控制台开通 对象存储OSS服务
新建一个 Bucket 列表
Java对接 OSS参考链接:https://help.aliyun.com/document_detail/32009.html
导入 OSS 的 SDK依赖
| <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency>
|
如果使用的是Java 9及以上的版本,则需要添加jaxb相关依赖
| <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency>
<dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.3</version> </dependency>
|
定义 OSSUploadService 对接文件上传
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
| @Service public class OSSUploadService {
public String OssUploadFile(MultipartFile file) { String endpoint = "yourEndpoint"; String accessKeyId = "yourAccessKeyId"; String accessKeySecret = "yourAccessKeySecret"; String bucketName = "examplebucket";
OSS ossClient = null; try { ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); InputStream inputStream = file.getInputStream(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String datePath = simpleDateFormat.format(new Date()); String originalFilename = file.getOriginalFilename(); String imgSuffix = originalFilename.substring(originalFilename.lastIndexOf(".")); String fileNmae = UUID.randomUUID().toString() + imgSuffix;
String finalURL = datePath + "/" + fileNmae; ossClient.putObject(bucketName, finalURL, inputStream);
return "https://" + bucketName + "." + endpoint + "/" + fileNmae; } catch (Exception e) { e.printStackTrace(); return "出错了"; } finally { ossClient.shutdown(); } } }
|
相关参数的获取
endpoint
accessKeyId,yourAccessKeySecret