依赖:
<!--阿里云-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.6</version>
</dependency>
yml配置:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/tlias
username: root
password: 1234
servlet:
multipart:
max-file-size: 10MB # 单个文件默认最大1MB
max-request-size: 100MB # 一次多个文件默认最大10MB
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
aliyun:
oss:
endpoint: oss-cn-beijing.aliyuncs.com
accessKeyId: LTAI5tQ823aWxiqK2BmKxyeN
accessKeySecret: 0CYrcWVlpnNJdm7Zn1R53iyEcXbGbM
bucketName: tlias-web-management-yn
url: https://tlias-web-management-yn.oss-cn-beijing.aliyuncs.com
配置类:
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss") // 读取配置信息
public class OssProperties {
// 服务器区域
private String endpoint;
// 秘钥key
private String accessKeyId;
// 秘钥
private String accessKeySecret;
// 存储空间
private String bucketName;
// 访问域名
private String url;
}
阿里存储工具类:
@Component
public class OssTemplate {
//注入配置参数实体类对象
@Autowired
private OssProperties ossProperties;
//文件上传
public String upload(String fileName, InputStream inputStream) {
//创建客户端
OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
//设置文件最终的路径和名称
String objectName = "images/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
+ "/" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
//meta设置请求头,解决访问图片地址直接下载
ObjectMetadata meta = new ObjectMetadata();
meta.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
//上传
ossClient.putObject(ossProperties.getBucketName(), objectName, inputStream, meta);
//关闭客户端
ossClient.shutdown();
return ossProperties.getUrl() + "/" + objectName;
}
//文件后缀处理
private String getContentType(String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase(".bmp")) {
return "image/bmp";
}
if (FilenameExtension.equalsIgnoreCase(".gif")) {
return "image/gif";
}
if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
FilenameExtension.equalsIgnoreCase(".jpg") ||
FilenameExtension.equalsIgnoreCase(".png")) {
return "image/jpg";
}
return "image/jpg";
}
}
实现类:
@RestController
public class FileController {
@Autowired
private OssTemplate ossTemplate;
// 文件上传
@PostMapping("/upload")
public Result uploadFile(MultipartFile image) throws IOException {
// 调用阿里云工具类上传文件
String filePath = ossTemplate.upload(image.getOriginalFilename(), image.getInputStream());
// 返回文件路径
return Result.success(filePath);
}
}