菜鸡程序员进阶之路——初入职场,要写一个图片上传的功能接口,搞定它。 Controller层接收参数,因为我是要同时上传多张图片,所以用数组接收 MultipartFile[] ,一张图片就只用MultipartFile就行了。 翠花,上代码. @PostMapping("uploadFiles") @ResponseBody public List<String> uploadFiles(@ApiParam("只支持jpg图片格式,可以一次上传多张图片") @RequestParam("files") MultipartFile[] files){ List<String> strings = fileService.uploadFiles(files); return strings; } controller层很简单,只做参数的接收,处理数据到业务层 service层: import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; @Service @Slf4j public class FileService { @Autowired private MongoTemplate mongoTemplate; private static final List ALLOW_IMAGE_TYPE = Arrays.asList("image/jpeg"); /** * 图片上传 * @Param files * @return */ public List<String> uploadFiles(MultipartFile[] files) { List<String> list = new ArrayList<>(); for (int i = 0; i < files.length; i++) { //判断图片类型 String imageType = files[i].getContentType(); if (!ALLOW_IMAGE_TYPE.contains(imageType)){ log.info("图片类型错误!"); throw new EqException(ExceptionEnum.IMAGE_TYPE_ERROR); } //解析图片内容 BufferedImage bufferedImage = null; try { bufferedImage = ImageIO.read(files[i].getInputStream()); } catch (IOException e) { log.info("解析图片失败!",e.getMessage()); throw new EqException(ExceptionEnum.IMAGE_TYPE_ERROR); } if (bufferedImage == null){ log.info("解析图片失败!"); throw new EqException(ExceptionEnum.IMAGE_TYPE_ERROR); } //设置上传图片名称 long time = new Date().getTime(); String imageName = time + ".jpg"; //得到上传文件夹对象 File imagePathFile = new File(EqConstants.IMG_PATH); //上传图片 try { files[i].transferTo(new File(imagePathFile,imageName)); } catch (IOException e) { log.info("图片上传失败!"); throw new EqException(ExceptionEnum.FILE_UPLOAD_ERROR); } list.add(EqConstants.IMG_URL+imageName); } return list; } } service层将图片解析,然后输出到自定义的目录,输出完毕后把图片的路径返回。 自定义的文件存放路径和返回路径前缀 public class EqConstants { //上传路径 public static final String IMG_PATH = "D:\\develop\\nginx-1.18.0\\file\\images"; //访问路径 // public static final String IMG_PATH = projectPath()+"\\images"; public static final String IMG_URL = "http://image.equip.com/images/"; /** * 获取当前项目路径 */ public static String projectPath(){ String projectPath = System.getProperty("user.dir"); System.out.println("projectPath==" + projectPath); return projectPath; } } 最后,让我们用Postman来测试一下。 |
上传成功,返回连接
OK!测试成功