获取对象
@Resource
private ALiYunConfig aLiYunConfig;
代码配置类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 描述:
*
* @author zhaofeng
* @date 2023-09-05
*/
@Data
@ConfigurationProperties(prefix = "aliyun")
@Component
public class ALiYunConfig {
/**
* 阿里云keyId
*/
private String accessKey ;
/**
* 阿里云secret
*/
private String accessSecret;
/**
* 阿里云secret
*/
private String endpoint;
/**
* 阿里云oss上传节点
*/
private String ossEndpoint;
/**
* 阿里云oss Bucket名称
*/
private String ossBucketName;
}
yml配置 注意这些参数都是事先配置好的(也就是注册阿里云购买过的获取的参数)
代码controller层
/**
* 用户上传图片接口
*
* @param file
*/
@ApiOperation("用户上传图片接口")
@PostMapping("uploadPicture")
@ExcludeLogin
public String uploadPicture(@RequestParam(name = "file") MultipartFile file) {
return iPlatformPictureService.uploadPicture(file);
}
代码service层
@Resource
private ALiYunConfig aLiYunConfig;
/**
* 图片上传到阿里云
*
* @param file
* @return
*/
@Override
public String uploadPicture(MultipartFile file) {
//源文件名称
String fileName = file.getOriginalFilename();
//获取后缀
String suffixName = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1) : null;
//校验图片格式
if (StringUtils.isBlank(suffixName)) {
throw new BusinessException(PlatformResultCode.PICTURE_ERROR);
}
List<String> suffix = Arrays.asList("PNG", "JPG", "JPEG");
if (!suffix.contains(suffixName.toUpperCase())) {
throw new BusinessException(PlatformResultCode.PICTURE_ERROR);
}
//校验图片大小 校验图片大小
long size = file.getSize();
int sizeKb = (int) ((size / 1024) + 1);
//从缓存中获取图片大小的配置
int configValue = platformConfigExport.getConfigInteger(PlatformConfigEnum.PICTURE_SIZE);
if (sizeKb > configValue) {
throw new BusinessException(PlatformResultCode.PICTURE_MAX, configValue / 1024);
}
//拼接文件夹以及文件名称
String today = DateUtils.today();
String name = today + "/" + UUIDUtils.getUUID() + "." + suffixName;
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = aLiYunConfig.getOssEndpoint();
// 填写Bucket名称,例如examplebucket。
String bucketName = aLiYunConfig.getOssBucketName();
OSS ossClient = new OSSClientBuilder().build(endpoint, aLiYunConfig.getAccessKey(), aLiYunConfig.getAccessSecret());
try {
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, name, file.getInputStream());
// 上传文件
PutObjectResult result = ossClient.putObject(putObjectRequest);
} catch (Exception e) {
log.error("PlatformPictureServiceImpl.uploadPicture; 用户上传图片失败,大小:{}Kb,", sizeKb, e);
throw new BusinessException(PlatformResultCode.UPLOAD_PICTURE_ERROR);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//返回路径,该路径在浏览器访问可以下载
return "https://" + aLiYunConfig.getOssBucketName() + "." + endpoint + File.separator + name;
}