package com.you.util;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @author: You
* @date: 2024/1/13 17:25
* @description 文件工具类 完成图片文件上传
*/
public class FileUtil {
//编写方法完成模块中,对于图片上传的校验与上传功能
/**
* 用于文件上传功能
* @param file
* @param servicePath
* @param localPath 上传文件的本地目录(服务器端)
* @return
*/
public String upload(MultipartFile file,String servicePath,String localPath){
//文件上传
//1.文件必须存在 是一个具体的文件
//获取文件的原名称
String filename = file.getOriginalFilename();
//非空校验
if (filename != null && !filename.isEmpty()) {
//2.文件格式的图片信息 jpg png gif
//校验格式 将名字后缀转换为小写
filename = filename.toLowerCase();
//匹配正则表达式
if (!filename.matches("^.+\\.(jpg|png|gif)$")){
return null;
}
//3.防止木马病毒等 伪装上传
try {
//校验文件是否真的为一张图片,如果是一张图片,图片是有长度和高度的
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
//获取图片的长度和高度
int height = bufferedImage.getHeight();
int width = bufferedImage.getWidth();
//判断文件是否合法
if (width == 0 || height == 0) {
return null;
}
//4.上述3步校验完成后再进行文件上传
//具体需要的上传路径
//当前项目的 /static/images/course/ 上传日期 /文件.jpg
//String localPath="/static/images/course/";
//获取日期路径
String datePath= new SimpleDateFormat("yyyyMMdd/").format(new Date());
//拼接成当前上传文件的项目目录路径
String dirPath = localPath + datePath;
File file1=new File(servicePath+dirPath);
if (!file1.exists()){
file1.mkdirs();
}
//需要上传具体的上传路径、对文件进行重命名
String uuid= UUID.randomUUID().toString();
//获取文件的格式 。jpg 。png 。gif
int index=filename.lastIndexOf(".");
filename=uuid+filename.substring(index);
//拼接需要上传文件的全路径 目录+名称
String realPath=dirPath+filename; //文件基于当前项目的具体路径
//将文件上传到服务器上
file.transferTo(new File(servicePath+realPath));
System.out.println(servicePath+realPath);
//将路径参数保存在将要传递给数据库的对象中
return realPath;
}catch (Exception e){
e.printStackTrace();
}
}
//如果没有文件 直接返回null
return null;
}
}
文件上传工具类FileUtil 实现图片文件上传到服务器中
最新推荐文章于 2024-05-13 11:25:08 发布