步驟: 1. 先把文件上傳到本地 2.使用google Thumbnails壓縮圖片 3. 壓縮的圖片上傳OSS 4.刪除本地文件
OSS工具類沒提供了,隨便百度一個都行的
import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import net.coobird.thumbnailator.Thumbnails; import org.apache.commons.io.FileUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; /** * 通用請求處理 * * @author ruoyi */ @RestController @Slf4j @Api(description = "文件上傳") public class CommonController { /** * 通用上傳請求 */ @ApiOperation("文件上傳") @PostMapping("/oss/upload") public ApiResult uploadFile(MultipartFile file) throws Exception { try { return ApiResult.success(OssUtil.fileUpload(file)); } catch (Exception e) { log.error("文件上傳失敗 {}", e); return ApiResult.error(e.getMessage()); } } @ApiOperation("文件上傳-壓縮") @PostMapping("/oss/upload1") public ApiResult uploadPicture1(MultipartFile multipartfile) throws Exception { 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 = new File(contextPath); //生成圖片文件 FileUtils.copyInputStreamToFile(multipartfile.getInputStream(), tempFile);
//壓縮圖片 Thumbnails.of(contextPath) .scale(1f) .outputQuality(0.5f) .toFile(contextPath); //獲取壓縮后的圖片 f = new File(contextPath); inputStream = new FileInputStream(f); return ApiResult.success(OssUtil.fileUpload(inputStream, multipartfile.getOriginalFilename())); } catch (Exception e) { log.error("圖片上傳失敗 {}", e); throw new Exception("圖片上傳失敗"); } finally { //將臨時文件刪除 tempFile.delete(); f.delete(); inputStream.close(); } } /** * 獲取文件擴展名 * * @param filename 文件名 * @return */ public static String 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); } } return filename; } /** * 獲取不帶擴展名的文件名 * * @param filename 文件 * @return */ private static String getFileNameWithoutEx(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot > -1) && (dot < (filename.length()))) { return filename.substring(0, dot); } } return filename; }
