增加依赖jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
修改springmvc.xml配置文件,添加
<!-- 启用文件上传支持 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
<property name="maxInMemorySize" value="10240" />
</bean>
controller代码
package com.test.controller; import java.io.IOException;
import java.util.List; import javax.annotation.Resource; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView; import net.sf.json.JSONObject; @Controller
public class ServiceDBController { private static Log log = LogFactory.getLog(ServiceDBController.class); @RequestMapping(value="test.do")
public void test(@RequestParam("myFile")MultipartFile myFile) {
//处理文件
}
}
表单
<form action="${pageContext.request.contextPath}/test.do" method="post" id="frm-uploadfile" enctype="multipart/form-data">
<input type="file" name="myFile" /> <!--注意这个name要和对应的spring的controller参数名称相同-->
<input type="submit" value="上传文件">
</form>