先写html
这里就是用了一个 FormData(注意大小写)然后传值
<form id="save">
<p><input type="file" name="file"></p>
<input type="button" value="上传" onclick="save()">
</form>
<script src="js/jquery-3.2.1.js"></script>
<script>
function save() {
var formdata = new FormData($("#save")[0]);
$.ajax({
url:"/save/imges",
type:"post",
data:formdata,
contentType: false,//这两个一定要加
processData: false,
success:function (data) {
}
})
}
</script>
@controller
@Controller
@RequestMapping("/save")
public class SvaeImage {
@RequestMapping("/imges")
@ResponseBody
public void save(MultipartFile file){
//上传的路径
String path ="F:/saveimage/aaa/";
File filepath = new File(path);
//不存在就创建文件
if(!filepath.exists()){
filepath.mkdir();
}
//获取文件名字
String name = file.getOriginalFilename();
//获取后缀
String suf = name.substring(name.lastIndexOf(".")+1);
//这里的时间格式注意一下,我要用时间作为文件名字所以注意特殊字符不要出现 如 “ : ”等,
//如果不用可以省略这一步
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
Date date =new Date();
String time= sf.format(date);
//这里是字符串的拼接,生成文件的名字,我这里是用的时间+文件后缀命名的
String newname = time+"."+suf;
File file1 = new File(path+newname);
try {
//创建文件
file.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
###到这里其实已经可以了,就是上传默认有大小的限制,下面告诉spring boot 的解决方法,先看效果
这是要传的照片
点击上传
在springboot2.0上面配置上传文件大小限制
1.application.properties
spring.servlet.multipart.max-file-size=50Mb
spring.servlet.multipart.max-request-size=200Mb
1.application.yml
yml配置文件,注意格式空格不要少也不要多
spring:
servlet:
multipart:
enabled: true
max-file-size: 20MB
max-request-size: 200MB