pom文件增加图片压缩依赖包
<!-- 图片压缩 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<!-- 阿里云对象存储 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
增加图片上传工具类OSSUplodFile.java
package com.common.utils;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 文件上传工具类
*/
public class OSSUplodFile {
private static final Logger logger = LoggerFactory.getLogger(OSSUplodFile.class);
/*阿里云oss上传文件方式*/
//密匙keyId 可以在阿里云获取到
public static String accessId="你的阿里云accessId";
//密匙keySecret 可以在阿里云获取到
public static String accessKey="你的阿里云accessKey";
//你的oss所在域,要加http:// 不明白可以对照你的文件引用地址
public static String endpoint="oss-cn-beijing.aliyuncs.com";
//你的bucketName存储桶 名称 即是你的OSS对象名称 不明白查oss开发文档专业术语
public static String bucket="ceshiceshi";
private static String baseUrl="https://ceshiceshi.oss-cn-beijing.aliyuncs.com/";
private static OSSClient ossClient = new OSSClient(endpoint, accessId, accessKey);
/**
* 后台通过服务器间接传文件
* @param file
* @return
* @throws IOException
*/
public static Map<String, Object> createUpload(@RequestParam("file") MultipartFile file) throws Exception {
ObjectMetadata objectMetadata = new ObjectMetadata();
String fileName = file.getOriginalFilename();
String uuid = GeneratorUtil.genFileName();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
String date = df.format(new Date());// new Date()为获取当前系统时间,也可使用当前时间戳
byte[] bytes = file.getBytes();
//调用图片压缩方法,这里压缩到100k左右
bytes = compressPicForScale(bytes,100);
InputStream sbs = new ByteArrayInputStream(bytes);
objectMetadata.setContentLength(bytes.length);
objectMetadata.setContentType(file.getContentType());
//获取文件后缀名
String ext = FilenameUtils.getExtension(file.getOriginalFilename());
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, "ceshi/"+date+uuid+ext, sbs, objectMetadata);
PutObjectResult re = ossClient.putObject(putObjectRequest);
Map<String, Object> data = new HashMap<>();
data.put("url", baseUrl + "ceshi/" + date+uuid+ext);
data.put("code", 200);
data.put("msg", "成功");
data.put("size", file.getSize());
return data;
}
/*
* 以下是常量,按照阿里代码开发规范,不允许代码中出现魔法值
*/
private static final Integer ZERO = 0;
private static final Integer ONE_ZERO_TWO_FOUR = 1024;
private static final Integer NINE_ZERO_ZERO = 900;
private static final Integer THREE_TWO_SEVEN_FIVE = 3275;
private static final Integer TWO_ZERO_FOUR_SEVEN = 2047;
private static final Double ZERO_EIGHT_FIVE = 0.85;
private static final Double ZERO_SIX = 0.6;
private static final Double ZERO_FOUR_FOUR = 0.44;
private static final Double ZERO_FOUR = 0.4;
/**
* 根据指定大小压缩图片
*
* @param imageBytes 源图片字节数组
* @param desFileSize 指定图片大小,单位kb
* @return 压缩质量后的图片字节数组
*/
public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
if (imageBytes == null || imageBytes.length <= ZERO || imageBytes.length < desFileSize * ONE_ZERO_TWO_FOUR) {
return imageBytes;
}
long srcSize = imageBytes.length;
double accuracy = getAccuracy(srcSize / ONE_ZERO_TWO_FOUR);
try {
while (imageBytes.length > desFileSize * ONE_ZERO_TWO_FOUR) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
Thumbnails.of(inputStream)
.scale(accuracy)
.outputQuality(accuracy)
.toOutputStream(outputStream);
imageBytes = outputStream.toByteArray();
}
logger.info("图片原大小={}kb | 压缩后大小={}kb",
srcSize / ONE_ZERO_TWO_FOUR, imageBytes.length / ONE_ZERO_TWO_FOUR);
} catch (Exception e) {
logger.error("【图片压缩】msg=图片压缩失败!", e);
}
return imageBytes;
}
/**
* 自动调节精度(经验数值)
*
* @param size 源图片大小
* @return 图片压缩质量比
*/
private static double getAccuracy(long size) {
double accuracy;
if (size < NINE_ZERO_ZERO) {
accuracy = ZERO_EIGHT_FIVE;
} else if (size < TWO_ZERO_FOUR_SEVEN) {
accuracy = ZERO_SIX;
} else if (size < THREE_TWO_SEVEN_FIVE) {
accuracy = ZERO_FOUR_FOUR;
} else {
accuracy = ZERO_FOUR;
}
return accuracy;
}
}
增加文件上传接口
package com.web.controller;
import com.common.utils.OSSUplodFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
@Controller
@RequestMapping("/api/aliyun")
@Api(tags="文件上传API")
public class AliyunUploadController {
@PostMapping("/upload")
@ApiOperation(value = "文件上传oss方式")
public @ResponseBody
Map<String, Object> ossUpload(@RequestParam("file") MultipartFile file) {
try {
Map<String, Object> map = OSSUplodFile.createUpload(file);
return map ;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
原文链接:https://blog.csdn.net/wgh0315/article/details/121290565