1. 引入jar包
commons-io-2.4.jar
commons-fileupload-1.2.2.jar
2. 页面代码
4.1 页面-表单提交
~~~
<form action="../upload" id="form1" method="post" enctype="multipart/form-data">
<input type="text" name="uname"/>
<input type="file" name="photo" multiple="multiple" accept="image/*" onchange="preview(this)"/>
<button type="submit">提交</button>
</form>
~~~
4.2 页面-ajax提交
~~~
<form action="../upload" id="form1" method="post" enctype="multipart/form-data">
<input type="text" name="uname"/>
<input type="file" name="photo" multiple="multiple" accept="image/*" onchange="preview(this)"/>
<button type="button" onclick="doupload()">提交</button>
</form>
<script>
function doupload()
{
var form=document.getElementById("form1");
var fd =new FormData(form);
$.ajax({
url: "../upload",
type: "POST",
data: fd,
dataType:"json",
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function(data){
console.log(data.result);
}
});
}
</script>
~~~
3. springmvc 配置文件
~~~
<!-- 文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
~~~
4. 控制器代码
单文件上传
~~~
@RequestMapping("/register")
public String reg(Userinfo u, String[] hobby, MultipartFile upload)
{
//文件上传
String filename = System.currentTimeMillis()+upload.getOriginalFilename();
//
File dest = new File("E:/apache-tomcat-8.0.29/webapps/upload",filename);
try {
//把文件从临时文件拷贝到目标地址上
upload.transferTo(dest);
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
~~~
多文件上传(注意,如果上传多个文件时错误,需要加@RequestParam注解)
~~~
@RequestMapping("/upload")
@ResponseBody
public String upload(String uname, @RequestParam MultipartFile[] photo)
{
System.out.println(uname);
for(int i=0; i<photo.length;i++)
{
System.out.println(photo[i].getOriginalFilename());
File f = new File("d:/io",filename);
try {
photo.transferTo(f);
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "{\"result\":true}";
}
~~~
5. 文件预览
~~~
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/jquery-3.2.1.js"></script>
<script>
function preview(obj)
{
for(var i=0; i<obj.files.length;i++)
{
var file = obj.files[i];
//限定上传文件的类型,判断是否是图片类型
if (!/image\/\w+/.test(file.type)) {
alert("只能选择图片");
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
//base64Code=e.target.result;
base64Code=this.result;
$("#preview").append('<img width="200px" src="'+base64Code+'"/>');
}
}
}
</script>
</head>
<body>
<input type="file" multiple="multiple" accept="image/*" onchange="preview(this)"/> // accept="image/*"在手机上只弹出手机图库
<div id="preview"></div>
</body>
</html>
~~~