在pom.xml中引入依赖配置
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
在springMVC配置文件中添加如下配置
<!-- springMVC文件上传 -->
<!-- 定义文件上传解析器 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>32505856</value><!-- 上传文件大小限制为31M,31*1024*1024 -->
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property></bean>
在前面jsp页面中添加表单,包含文件上传控件
<form action="<%=editMemberUrl%>" id="myform" method="post"
enctype="multipart/form-data" >
<div class="col-md-5">
<input class="" type="file" name="file" />
<input type="hidden" name="pic1" id="coverImg1" value="${member.pic1 }" />
<input type="button" value="上传" onclick="upload()" />
<img id="coverImg2" src="${member.pic1 }" style="width: 50px; height: 50px;" />
</div>
</form>
添加ajax请求
<script>
function upload() {
alert("开始上传文件!")
var formData = new FormData(document.getElementById("myform"));
$.ajax({
url : "${ctx}/file/upload.html",
type : "post",
data : formData,
processData : false,
contentType : false,
success : function(data) {
if (data != "0") {
alert("上传成功:" + data);
$('#coverImg1').val(data);
$('#coverImg2').attr("src", "${ctx}/" + data);
} else {
alert("上传失败")
}
}
});
}
</script>
添加文件上传控制类
@Controller
@RequestMapping("/file")
public class FileUploadController {
//ajax单个文件上传,返回json串
@ResponseBody
@RequestMapping("/upload")
public String fileupload3(HttpServletRequest req, @RequestParam("file") MultipartFile myfile)
throws IOException, ServletException {
System.out.println("文件上传测试。。。" + myfile);
if (!myfile.isEmpty()) {
String name = myfile.getOriginalFilename();
String suffix = name.substring(name.lastIndexOf("."), name.length());
String filename = UUID.randomUUID() + suffix;
System.out.println(filename);
InputStream is = myfile.getInputStream();
String serverpath = req.getSession().getServletContext().getRealPath("/upload");
System.out.println("服务器路径:" + serverpath);
FileOutputStream fos = new FileOutputStream(serverpath + File.separator + filename);
byte[] bty = new byte[4096];
int length = 0;
while ((length = is.read(bty)) != -1) {
fos.write(bty, 0, length);
}
fos.close();
is.close();
req.setAttribute("file", "upload" + File.separator + filename);
//return "upload/success";
return "upload" + File.separator + filename;
}
//return "upload/fail";
return "0";
}
}