关于spring:实现上传图片

8次阅读

共计 2228 个字符,预计需要花费 6 分钟才能阅读完成。

封装 VO 对象

@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class ImageVO {
 private Integer error;// 谬误提醒 0 程序运行失常 1. 文件上传有误
 private String url;// 图片拜访的虚构门路
 private Integer width;
 private Integer heigth;
 // 设定上传失败的办法
 public static ImageVO fail(){return  new ImageVO(1,null,null,null);
 }
 // 胜利
 public static ImageVO success(String url,Integer width,Integer heigth){return  new ImageVO(0,url,width,heigth);
 }
}

FileController 层

@RequestMapping("/pic/upload")
public ImageVO upload(MultipartFile uploadFile) throws IOException {return fileService.upload(uploadFile);
}

FileServiceImpl 层

@Service
public class FileServiceImpl implements FileService{
 // 筹备一个存储图片的文件夹
 private String rootpath="C:/jt";
 //1.2 筹备图片的汇合
 private static Set<String> imageTypeSet;
 static {imageTypeSet=new HashSet<>();
 imageTypeSet.add(".jpg");
 imageTypeSet.add(".png");
 imageTypeSet.add(".gif");
 }
 /**
 * 校验:* 1. 校验是否为图片
 * 2. 校验是否为歹意的程序
 * 3. 避免文件数量太多,分目录存储
 * 4. 避免文件重名
 * 实现文件上传
 * @param uploadFile
 * @return
 * @throws IOException
 */
 @Override
 public ImageVO upload(MultipartFile uploadFile) throws IOException {
 //1. 常见图片类型 jpg|png|gif…… //1.1 获取以后图片的名称之后截取其中的类型
 String fileName=uploadFile.getOriginalFilename();
 int index = fileName.lastIndexOf(".");
 String fileType = fileName.substring(index);
 // 转换为小写
 fileType= fileType.toLowerCase();
 //1.3 判断图片类型是否正确
 if(!imageTypeSet.contains(fileType)){return ImageVO.fail();// 图片类型不匹配
 }
 //2. 歹意校验 依据宽度 / 高度进行校验
 //2.1 利用工具 API 对象 读取字节信息 获取图片对象类型
 try{BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
 //2.2 校验是否有高度和宽度
 int width=bufferedImage.getWidth();
 int height=bufferedImage.getHeight();
 if (width==0||height==0)
 return ImageVO.fail();
 //3. 避免文件数量太多,分目录存储
 //3.1 将工夫依照指定的格局要求 转化为字符串
 String dateDir = new SimpleDateFormat("/yyyy/MM/dd/")
 .format(new Date());
 //3.2 拼接文件存储的目录对象
 String fileDir=rootpath+dateDir;
 File dirFile=new File(fileDir);
 //3.3 动态创建目录
 if(!dirFile.exists()){dirFile.mkdirs();
 }
 //4 避免文件重名
 //4.1 动静生成 uuid
 String uuid=
 UUID.randomUUID().toString().replace("-","");
 String realFileName=uuid+fileType;
 //5 实现文件上传
 //5.1 拼接文件实在门路
 String realFilePath=fileDir+realFileName;
 //5.2 封装对象 实现上传
 File realFile=new File(realFilePath);
 uploadFile.transferTo(realFile);
 String url="https://img.alicdn.com/imgextra/i1/2978217349/O1CN01EwgFIG249tI2uaFx3_!!0-item_pic.jpg_430x430q90.jpg";
 return ImageVO.success(url,width,height);
 }catch (Exception e){e.printStackTrace();
 return ImageVO.fail();}
 }}
正文完
 0