文件上传
在application.properties 限制文件属性
表单上传
spring.servlet.multipart.max-file-size=1KB
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data" >
<input type="file" name="file">
<input type="submit" value="提交">
</form>
</body>
</html>
@RestController
public class FileuploadApplication {
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest request){
String format = sdf.format(new Date());
//getServletContext().getRealPath("/")获取web站点在硬盘中的绝对路径
String realPath = request.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=
request.getScheme()+"://"+request.getServerName()+":"
+request.getServerPort()+"/img"+format+newName;
return url;
}catch (IOException e){
e.printStackTrace();
}
return "error";
}
}
ajax上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.5.1.min.js"></script>
</head>
<body>
<div id="result"></div>
<input type="file" id="file">
<input type="button" value="上传" onclick="uploadFile()">
</body>
<script type="text/javascript">
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,
success:function (msg) {
$("#result").html(msg);
}
})
}
</script>
</html>
多文件上传
@PostMapping("/uploads")
public String uploads(MultipartFile[] files, HttpServletRequest request){
String format = sdf.format(new Date());
//getServletContext().getRealPath("/")获取web站点在硬盘中的绝对路径
String realPath = request.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=
request.getScheme()+"://"+request.getServerName()+":"
+request.getServerPort()+"/img"+format+newName;
System.out.println(url);
}catch (IOException e){
e.printStackTrace();
}
}
return "success";
}