public class FileUpload{
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/upload")
public String upload(MultiparFile file,HttpServletRequest req){
String format = sdt.format(new Date());
String realPath = req.getServletContext().getRealPath("/img")+format;
File folder = new File(realPath);
if(!folder.exists){
folder.mkdirs();
}
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;
return url
}catch(Exception){}
return "error";
}
}
<form action="/upload" method="post" enctype="multipart/form-data">
<input type ="file" name="file">
<input type="submit" value="提交">
</form>
ajax页面版:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquer3.3.1.js"></script>
</head>
<body>
<div id="result"></div>
<input type="file" id="file">
<input type="button" value="上传" onclick="uploadFile()">
<script>
function uploadFile(){
var file = $("#file")[0].files[0];
var formData = new FormData();
formData.append("file",file);
$.ajax({
type:'post',
url:'/upload',
processData:false,
contentType:false,
data:formData,
sucess:function(msg){
$("#result").html(msg);
}
})
}
</script>
</body>