index.html
<div>
<form method="post" action="upload.html" enctype="multipart/form-data" id="sub">
<input type="text" name="name" />
<input type="file" name="file" />
<input type="button" value="提交表单" οnclick="doit();"/>
</form>
<script>
function doit(){
$("#sub").submit();
}
</script>
</div>
SPRING MVC config file xxx-servlet.xml
<context:component-scan base-package="net.spring.controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" >
<property name="maxUploadSize">
<value>1048576</value>
</property>
FileOperateController.java
package net.spring.controller;
import java.io.File;
import java.util.Date;
import javax.servlet.ServletContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class FileOperateController implements ServletContextAware {
private ServletContext servletContext;
@RequestMapping(value = "/upload")
public ModelAndView upload(@RequestParam("name") String name,
@RequestParam("file") CommonsMultipartFile mFile) throws Exception {
System.out.println("mFile:"+mFile.isEmpty());
System.out.println("name:"+name);
if (!mFile.isEmpty()) {
String path = this.servletContext.getRealPath("/") + "temp/"; // 获取本地存储路径
File abpath = new File(path);
if (!abpath.exists()) {
abpath.mkdir();
}
File file = new File(path + mFile.getOriginalFilename()); // 新建一个文件
mFile.getFileItem().write(file);
return null; // 返回成功视图
} else {
return null; // 返回成功视图
}
}
@Override
public void setServletContext(ServletContext arg0) {
// TODO Auto-generated method stub
this.servletContext = arg0;
}
}