Java上传图片,java上传图片到文件服务器
picUploadResult.setImgPath(filePath); return picUploadResult; } catch (Exception e) { e.printStackTrace(); } picUploadResult.setLegal(false); return picUploadResult; }实现方法接口
单图片上传
public PicUploadResult uplodadImg(MultipartFile multipartFile, HttpServletRequest request) { return uploadImgMethod(multipartFile, request); }
多图片上传
public PicUploadResult uploadManyImg(MultipartFile[] uploadFile, HttpServletRequest request) { List<String> imgPaths = new ArrayList<>(); for (MultipartFile multipartFile : uploadFile) { PicUploadResult picUploadResult = uploadImgMethod(multipartFile, request); if(picUploadResult.isLegal()){ imgPaths.add(picUploadResult.getImgPath()); }else{ return picUploadResult; } } PicUploadResult picUploadResult = new PicUploadResult(); picUploadResult.setLegal(true); picUploadResult.setImgPahts(imgPaths); return picUploadResult; }
实现方法补充
// 项目上传至绝对路径(在yml里配置你的项目绝对路径) @Value("${file.save-path}") private String baseFilePath; // 项目根路径下的目录 -- SpringBoot static 目录相当于是根路径下(SpringBoot 默认) private final static String UPLOAD_PATH_PREFIX = "statics/uploadFile/";
控制层
public class FileUploadController { // 允许上传的格式 图片形式 private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".png"}; @Resource private FileUploadService fileUploadService; @PostMapping("/uploadImg") public R uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) { boolean isFlag = false; for (String type : IMAGE_TYPE) { System.out.println(file.getOriginalFilename()); if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) { isFlag = true; break; } } if (isFlag) { PicUploadResult picUploadResult = fileUploadService.uplodadImg(file, request); boolean isLegal = picUploadResult.isLegal(); if (isLegal) { Map resMap = new HashMap<>(); resMap.put("imgPath", picUploadResult.getImgPath()); return R.ok(resMap); } else { return R.error("图片上传有误"); } } else { return R.error("上传的图片格式必须为:bmp,jpg,jpeg,png"); } } @PostMapping("/uploadManyImg") public R uploadManyImg(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) { boolean isFlag = false; for (MultipartFile uploadFile : files) { for (String type : IMAGE_TYPE) { if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) { isFlag = true; break; } } } if (isFlag) { PicUploadResult picUploadResult = fileUploadService.uploadManyImg(files, request); boolean isLegal = picUploadResult.isLegal(); if (isLegal) { Map resMap = new HashMap<>(); resMap.put("imgPaths", picUploadResult.getImgPahts()); return R.ok(resMap); } else { return R.error("图片上传有误"); } } else { return R.error("上传的图片格式必须为:bmp,jpg,jpeg,png"); } }}
工具类
根据实际情况添加所需的字段
public class PicUploadResult{ private boolean isLegal; private String imgPath; private List<String> imgPahts;}
Postman
(仅用于个人学习编码记录,代码均参考于百度以及自己改进,如有疑问欢迎大家积极讨论)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持盛行IT。
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。