通过MultipartFile实现图片上传

前言:
文件的上传一般使用输入流InputStream用于参数的接收,后续使用输出流outputStream实现文件的输出
这里使用Spring框架下的MultipartFile类完成文件的上传
MultipartFile 封装了输入流/输出流
VO类–封装ImageVO与前端页面交互

@Data
@Accessors(chain=true)
@NoArgsConstructor
@AllArgsConstructor
public class ImageVO {
     
    //{"error":0,"url":"图片的保存路径","width":图片的宽度,"height":图片的高度}
    private Integer error;  //是否上传正确  0正常  1错误
    private String url;     //图片的虚拟访问路径
    private Integer width;  //图片固有属性
    private Integer height; //固有属性  
   //为了调用方便准备工具方法
    public static ImageVO fail() {
      
        return new ImageVO(1, null, null, null);
    }
    
    public static ImageVO success(String url,Integer width,Integer height) {
       
        return new ImageVO(0, url, width, height);
    }
}

Controller层

@RestController
public class FileController {
     
    @Autowired
    private FileService fileService;
    
    @RequestMapping("/pic/upload")
    public ImageVO upload(MultipartFile uploadFile) {
     
        return fileService.upload(uploadFile);
    }
}

service层

public interface FileService {
     
	//图片上传
	public ImageVO upload(MultipartFile uploadFile);
}

service接口实现类

@Service
public class FileServiceImpl implements FileService{
     

	//图片存储路径
	private String localDir=D:/Download/;
	
	//图片虚拟访问路径(搭配nginx使用)
	private String urlPath=http://image.jt.com/;
	
	@Override
	public ImageVO upload(MultipartFile uploadFile) {
     
		
		//获取图片名称
		String fileName = uploadFile.getOriginalFilename();
		//将图片名称转换成小写字母
		fileName = fileName.toLowerCase();
		//正则表达式校验 是否为图片
		if(!fileName.matches("^.+\\.(png|jpg|gif)$")) {
     
			return ImageVO.fail();
		}
		//校验是否为恶意程序
		try {
     
			BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
			int width = bufferedImage .getWidth();
			int height = bufferedImage.getHeight();
			
			if(width == 0 || height ==0){
       //说明 上传的不是图片,为恶意程序.
				return ImageVO.fail();
			}
			
			//按照时间将目录进行划分 yyyy/MM/dd
			String deteDir = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
			String localFileDir  = localDir+deteDir;
			File file = new File(localFileDir);
			if(!file.exists()) {
     //如果目录不存在则创建多级目录
				file.mkdirs();
			}
			
			//动态生成文件名
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			//abc.jpg
			int index = fileName.lastIndexOf(".");
			String fileType = fileName.substring(index);//截取文件后缀
			String realFileName  = uuid + fileType;
			
			//文件上传
			String realFilePath = localFileDir + realFileName;
			File imageFile = new File(realFilePath);
			uploadFile.transferTo(imageFile);
			
			String url = urlPath+deteDir+realFilePath;
			return ImageVO.success(url, width, height);
		} catch (IOException e) {
     
			e.printStackTrace();
			return ImageVO.fail();
		}		
	}
}

你可能感兴趣的:(学习笔记,java,spring)