@Service
public class AppUploadServiceImpl implements AppUploadService {
@Value("${cos.secretId}")
private String secretId;
@Value("${cos.secretKey}")
private String secretKey;
@Value("${cos.region}")
private String region;
@Value("${cos.bucketName}")
private String bucketName;
/**
* 上传
* @param pics 需要上传的图片
* @param scale 缩小比例
* @param quality 压缩比例
* @return
* @throws IOException
*/
@Override
public List<String> upload(MultipartFile[] pics, float scale, double quality) throws IOException {
// 检查图片是否符合要求
if(pics == null || pics.length == 0){
return new ArrayList<>();
}
List<String> paths = new ArrayList<>();
for (MultipartFile pic : pics) {
String type = FileTypeUtil.getType(pic.getInputStream());
Assert.isTrue(!pic.isEmpty(), "图片错误");
Assert.isTrue(Arrays.asList("png", "jpg", "jpeg").contains(type.toLowerCase()), "不支持图片类型");
// 压缩图片
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Img.from(pic.getInputStream())
.scale(scale)
.setQuality(quality)
.write(outputStream);
// 上传到云存储
String key = UUID.randomUUID().toString();
String path = "image/" + key + "." + type;
PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucketName, path, new ByteArrayInputStream(outputStream.toByteArray()), null);
getClient().putObject(putObjectRequest);
// 组合获取图片访问链接
String picPath = "https://" + this.bucketName + ".cos." + this.region + ".myqcloud.com/" + path;
paths.add(picPath);
}
return paths;
}
private COSClient getClient(){
String secretId = this.secretId;
String secretKey = this.secretKey;
BasicCOSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
ClientConfig clientConfig = new ClientConfig();
clientConfig.setRegion(new Region(this.region));
clientConfig.setHttpProtocol(HttpProtocol.https);
clientConfig.setSocketTimeout(30*1000);
clientConfig.setConnectionRequestTimeout(30*1000);
return new COSClient(cred, clientConfig);
}
}
对象存储api文档:
https://console.cloud.tencent.com/cos/bucket
https://console.cloud.tencent.com/cam/capi