1、加入两个jar包,commons-fileupload-1.3.jar、commons-io-1.2.jar
2、在配置文件applicationContext.xml加上以下配置
- <!-- 定义文件解释器(文件上传) -->
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- 设置默认编码 -->
- <property name="defaultEncoding" value="utf-8"></property>
- <!-- 上传图片最大大小1M-->
- <property name="maxUploadSize" value="1048576"></property>
- </bean>
3、Controller层写java代码
- import java.io.File;
- import java.io.IOException;
- import javax.servlet.http.HttpServletRequest;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.multipart.MultipartFile;
- @Controller
- @RequestMapping("/file")
- public class FileController {
- @RequestMapping("/test.do")
- @ResponseBody
- public String test(MultipartFile file,HttpServletRequest request) throws IOException{
- System.out.println("comming!");
- String path = request.getSession().getServletContext().getRealPath("/images");
- System.out.println("path>>"+path);
- String fileName = file.getOriginalFilename();
- System.out.println("fileName>>"+fileName);
- File dir = new File(path, fileName);
- System.out.println("dir.exists()>>"+dir.exists());
- if(!dir.exists()){
- dir.mkdirs();
- }
- System.out.println("dir.exists()>>"+dir.exists());
- // MultipartFile自带的解析方法
- file.transferTo(dir);
- return "ok";
- }
- }
5、html和js
- <form id="test">
- 选择文件:<input data-role="none" type="file" name="file" width="120px">
- <button data-role="none" onclick="testUpload();">测试</button>
- </form>
- function testUpload(){
- var form = new FormData(document.getElementById("test"));
- $.ajax({
- url : url,
- data : form,
- type : 'post',
- processData:false,
- contentType:false,
- success : function(data){
- alert("成功")
- },
- error : function(data){
- }
- });
- }
这样就大功告成,上传的图片在tomcat目录的
\webapps\你的项目名\images
里面