/*
*功能描述:文件上传的工具类,自动生成不重复的文件名
*/
public class FileUtil {
public static String getDatePath(){
Date date = new Date();
//格式化对象
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
return format.format(date);
}
public static String getFileNameNew(String filename){
Date date = new Date();
//格式化对象
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
String datestr = format.format(date);
//获取随机数
int rd = (int)Math.random()*10000;
String uuid = UUID.randomUUID().toString().replace("-","");
return datestr+rd+uuid+"_"+filename;
}
public static void main(String[] args) {
String datePath = FileUtil.getDatePath();
System.out.println("datePath = " + datePath);
String fileNameNew = FileUtil.getFileNameNew("1.jpg");
System.out.println("fileNameNew = " + fileNameNew);
}
}
//必须使用post类型传输数据,必须加上enctype="multipart/form-data" 才能传送文件类型数据
<form action="${pageContext.request.contextPath}/user/doAddPhoto" method="post" enctype="multipart/form-data">
//上传照片
@RequestMapping("/doAddPhoto")
public String doAddPhoto(@RequestParam("file") MultipartFile file, int id, HttpServletRequest request,String picName) throws IOException {
if (!file.isEmpty()){//判断是否有文件上传,如果为空表示文件未上传
String fileNameNew = com.oracle.shop.util.FileUtil.getFileNameNew(file.getOriginalFilename());
String datePath = FileUtil.getDatePath();
// imgurl中保存的路径
UserProfilePhoto userPhoto = new UserProfilePhoto();
userPhoto.setPicUrl(datePath+"/"+fileNameNew);
userPhoto.setPicName(picName);
userPhoto.setUserId(id);
//设置文件保存的路径,需要注意,文件需要保存到static文件夹下,否则可能被拦截器拦截,导致图片加载不出来
File file1 = new File(request.getRealPath("")+"\\static\\img\\"+datePath+"\\");
if (!file1.exists()){
file1.mkdirs();
}
//文件保存的路径
File file2 = new File(request.getRealPath("")+"/static/img/"+datePath+"/"+fileNameNew);
file.transferTo(file2);
System.out.println(file2.getAbsolutePath());
PhotoService.insert(userPhoto);
return "redirect:/user/center";
}else {
return "redirect:/user/center";
}
}