importio.swagger.annotations.Api;importio.swagger.annotations.ApiOperation;importlombok.extern.slf4j.Slf4j;importnet.coobird.thumbnailator.Thumbnails;importorg.apache.commons.io.FileUtils;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.multipart.MultipartFile;importjavax.imageio.ImageIO;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.FileInputStream;importjava.io.InputStream;/*** 通用请求处理
*
*@authorruoyi*/@RestController
@Slf4j
@Api(description= "文件上传")public classCommonController {/*** 通用上传请求*/@ApiOperation("文件上传")
@PostMapping("/oss/upload")public ApiResult uploadFile(MultipartFile file) throwsException {try{returnApiResult.success(OssUtil.fileUpload(file));
}catch(Exception e) {
log.error("文件上传失败 {}", e);returnApiResult.error(e.getMessage());
}
}
@ApiOperation("文件上传-压缩")
@PostMapping("/oss/upload1")public ApiResult uploadPicture1(MultipartFile multipartfile) throwsException {if (multipartfile.getSize() > 20 * 1024 * 1024) {throw new Exception("上传图片大小不能超过20M!");
}//获取图片文件名(不带扩展名的文件名)
String prefixName =getFileNameWithoutEx(multipartfile.getOriginalFilename());//获取图片后缀名,判断如果是png的话就不进行格式转换,因为Thumbnails存在转png->jpg图片变红bug
String suffixName =getExtensionName(multipartfile.getOriginalFilename());//图片存储文件夹
String filePath = "web/src/main/resources/";//图片在项目中的地址(项目位置+图片名,带后缀名)
String contextPath = filePath + CommonUtils.getStringRandom(5) + prefixName + "." +suffixName;//存的项目的中模版图片
File tempFile = null;//上传时从项目中拿到的图片
File f = null;
InputStream inputStream= null;try{//图片在项目中的地址(项目位置+图片名,带后缀名)
tempFile = newFile(contextPath);//生成图片文件
FileUtils.copyInputStreamToFile(multipartfile.getInputStream(), tempFile);
//压缩图片
Thumbnails.of(contextPath)
.scale(1f)
.outputQuality(0.5f)
.toFile(contextPath);//获取压缩后的图片
f = newFile(contextPath);
inputStream= newFileInputStream(f);returnApiResult.success(OssUtil.fileUpload(inputStream, multipartfile.getOriginalFilename()));
}catch(Exception e) {
log.error("图片上传失败 {}", e);throw new Exception("图片上传失败");
}finally{//将临时文件删除
tempFile.delete();
f.delete();
inputStream.close();
}
}/*** 获取文件扩展名
*
*@paramfilename 文件名
*@return
*/
public staticString getExtensionName(String filename) {if ((filename != null) && (filename.length() > 0)) {int dot = filename.lastIndexOf('.');if ((dot > -1) && (dot < (filename.length() - 1))) {return filename.substring(dot + 1);
}
}returnfilename;
}/*** 获取不带扩展名的文件名
*
*@paramfilename 文件
*@return
*/
private staticString getFileNameWithoutEx(String filename) {if ((filename != null) && (filename.length() > 0)) {int dot = filename.lastIndexOf('.');if ((dot > -1) && (dot
}
}returnfilename;
}