1.单文件上传
/**
* 单文件上传
*/
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest req){
SimpleDateFormat sdf = new SimpleDateFormat("/yyy/MM/dd/");
//按照日期创建文件夹保存文件
String format = sdf.format(new Date());
//图片保存路径 图片保存在tomcat临时目录
String realPath = req.getServletContext().getRealPath("/img")+ format;
File folder = new File(realPath);
//如果文件夹是空就创建文件夹
if (!folder.exists()){
folder.mkdirs();
}
//获取文件名
String oldFilename = file.getOriginalFilename();
//生成新的文件名
String newName = UUID.randomUUID().toString()+ oldFilename.substring(oldFilename.lastIndexOf("."));
try {
//保存文件
file.transferTo(new File(folder,newName));
//返回图片路径
String url = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/img"+format+newName;
return url;
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}
2.多文件上传
/**
* 多文件上传
* @param files
* @param req
* @return
*/
@PostMapping("/uploads")
public String uploads(MultipartFile[] files, HttpServletRequest req) {
String format = sdf.format(new Date());
String realPath = req.getServletContext().getRealPath("/img") + format;
File folder = new File(realPath);
if (!folder.exists()) {
folder.mkdirs();
}
for (MultipartFile file : files) {
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
try {
file.transferTo(new File(folder, newName));
String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/img" + format + newName;
System.out.println(url);
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}