pom.xml
<!-- 图片压缩 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
压缩代码
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* @Author: zhoufangyuan
* @Date: 2021/6/16 17:06
*/
@Service
@Slf4j
public class AttachFileServiceImpl implements AttachFileService {
public static final String F = "F";
public static final String SEQ_FILE_ID = "seq_fileId";
@Autowired
private AttachFileMapper attachFileMapper;
@Autowired
private MinIoUtil minIoUtil;
@Value("${minio.bucketName}")
private String bucketName;
@Autowired
private SequenceService sequenceService;
@Override
public void insertAttachFile(MultipartFile mf, AttachFile attachFile){
try {
String sequenceId =sequenceService.getSequenceId(F, SEQ_FILE_ID, GlobalConstants.INTEGER_NUM_11);
attachFile.setFileId(sequenceId);
//minIoUtil.putObject(bucketName,mf,attachFile.getFileId());
uploadFile(mf,attachFile);
String url=minIoUtil.getObjectUrl(bucketName,attachFile.getFileId());
url=url.replace(ConfigContext.getConfigValue("minIo_target_ip"),ConfigContext.getConfigValue("minIo_domain_name"));
attachFile.setFileUrl(url);
attachFile.preInsert();
AttachFileService delProXy=(AttachFileService)AopContext.currentProxy();
delProXy.insert(attachFile);
}catch (Exception e){
log.error("上传失败",e);
}
}
/**
* 上传文件
*
* @param file 文件
* @return
*/
public void uploadFile(MultipartFile file, AttachFile attachFile) throws Exception {
// 拿到文件后缀名,例如:png
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
// 新的文件名
String fileName = attachFile.getFileId();
/**
* 判断是否是图片
* 判断是否超过了 100K
*/
if (isPicture(suffix) && (1024 * 1024 * 0.1) <= file.getSize()) {
// 在项目根目录下的 upload 目录中生成临时文件
File newFile = new File(AttachFileService.class.getResource("/").getPath() + fileName + "." + suffix);
// 小于 1M 的
if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.7f).toFile(newFile);
}
// 1 - 2M 的
else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.6f).toFile(newFile);
}
//2M-5m 以上的
else if ((1024 * 1024* 2) < file.getSize() && file.getSize() <= (1024 * 1024 * 5)) {
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.5f).toFile(newFile);
}
// 5m 以上的
else if ((1024 * 1024 * 5) < file.getSize()) {
Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.3f).toFile(newFile);
}
// 获取输入流
FileInputStream input = new FileInputStream(newFile);
// 转为 MultipartFile
//MultipartFile multipartFile = new MockMultipartFile("file", newFile.getName(), "text/plain", input);
FileItem fileItem = this.getMultipartFile(input,newFile.getName(),attachFile.getFileName());
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
// 开始上传
minIoUtil.putObject(bucketName,multipartFile,attachFile.getFileId());
//删除临时文件
newFile.delete();
}
// 不需要压缩,直接上传
else {
minIoUtil.putObject(bucketName,file,attachFile.getFileId());
}
}
/**
* 判断文件是否为图片
*/
public boolean isPicture(String imgName) {
boolean flag = false;
if (StringUtils.isBlank(imgName)) {
return false;
}
String[] arr = {"bmp", "dib", "gif", "jfif", "jpe", "jpeg", "jpg", "png", "tif", "tiff", "ico"};
for (String item : arr) {
if (item.equals(imgName)) {
flag = true;
break;
}
}
return flag;
}
/**
* 将流转换成fileItem
* @param fis
* @param fieldName
* @return
*/
private FileItem getMultipartFile(FileInputStream fis, String fieldName,String oldFileName){
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem(fieldName, "image/jpeg", true, oldFileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
}
实体类
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author zhoufangyuan
* @date 2021/06/21/05:33
*/
@Data
public class AttachFile extends Base {
public static final String STATUS_TEMP = "temp";
/**
* 附件id
*/
@ApiModelProperty(name = "fileId", value = "附件id", hidden = false)
private String fileId;
/**
* 附件文件名称
*/
@ApiModelProperty(name = "fileName", value = "附件文件名称", hidden = false)
private String fileName;
/**
* 文件内容类型
*/
@ApiModelProperty(name = "contentType", value = "文件内容类型", hidden = false)
private String contentType;
/**
* 附件保存URL地址
*/
private String fileUrl;
/**
* 附件文件大小
*/
@ApiModelProperty(name = "fileSize", value = "附件文件大小", hidden = false)
private Integer fileSize;
/**
* 附件文件类型:与表fuli_attachtype字段type_id一致
*/
@ApiModelProperty(name = "fileType", value = "附件文件类型:与表fuli_attachtype字段type_id一致", hidden = false)
private String fileType;
/**
* 附件状态:formal=正式的;temp=临时的
*/
@ApiModelProperty(name = "status", value = "附件状态:formal=正式的;temp=临时的", hidden = false)
private String status;
private int width;
private int height;
}