---
title: "springMVC上传文件例子"
author: "mywebcode"
date: "2013-11-09T12:33:00Z"
tags: []
slug: "springmvc"
draft: false
lastmod: "2014-04-30T09:09:10Z"
id: 2057849
url: "https://mywebcode.iteye.com/blog/2057849"
---

最近写的springMVC上传文件例子，有兴趣的同学可以参考一下：

Java类：

```
package com.spring.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;

@Controller
public class UploadImageController {
	
	@RequestMapping(value="upload/file",method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView uploadImages(@RequestParam(value = "file", required = false) MultipartFile file, 
			HttpServletRequest request, ModelMap model) {
		
		    ModelAndView mav =new ModelAndView();  
	        String path = request.getSession().getServletContext().getRealPath("images/uploadImages");  
	        String fileName = file.getOriginalFilename();  
//	        String fileName = new Date().getTime()+".jpg";  
	        System.out.println(path);  
	        File targetFile = new File(path, fileName);  
	        if(!targetFile.exists()){  
	            targetFile.mkdirs();  
	        }  
	  
	        //����  
	        try {  
	            file.transferTo(targetFile);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        //model.addAttribute("fileUrl", request.getContextPath()+"/uploadImages/"+fileName);  
	        mav.addObject("fileUrl", request.getContextPath()+"/images/uploadImages/"+fileName);
	        mav.setViewName("uploadSuccess");
		return mav;
		
	}

}
```

jsp上传页面：

```
  <body>
    <form action="upload/file" method="post" enctype="multipart/form-data">  
    <input type="file" name="file" /> 
    <input type="submit" value="上传" />
    </form>
    <img alt="" src="images/10.jpg">
    <img alt="" src="images/uploadImages/11.gif">
  </body>
```

jsp上传成功页面：

```
  <body>
                 上传成功<br>
    <img src="${fileUrl}" alt=""/> 
    <img  src="${fileUrl}"  alt=""/> 
    <a href="${fileUrl}">查看</a>
    <a href="${fileUrl}">查看</a>
  </body>
```

还要在spring配置文件中加入：

```
      <bean id="multipartResolver" 
           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         <!-- 设置上传文件大小的参数 -->
        <property name="maxUploadSize" value="1000000"/>
       </bean>
```

SpringMVC访问静态资源的配置：css,js,img

注意web.xml文件：

```
    <servlet-mapping> 
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern><!-- 拦截所有请求 ，会导致img,js,css等静态文件显示不了 ，要访问到静态文件要在配置文件中做处理-->
        <!-- <url-pattern>*。do</url-pattern> -->  <!-- 只拦截。do的请求，静态文件可以访问 -->
    </servlet-mapping>
```

注意applicationContext.xml配置文件加入如下代码；

```
     <mvc:annotation-driven />
    
    <!-- 取消对images和js两个文件夹的拦截，可以访问静态文件的文件夹 -->
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:default-servlet-handler />
        
       <!-- 自动扫描bean，把作了注解的类转换为bean -->  
      <context:component-scan base-package="com" />
```

运行效果：

![](http://img.blog.csdn.net/20131109123155734?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQva2VuaGlucw=%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FCenter)

运行效果2：

![](http://img.blog.csdn.net/20131109123205093?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQva2VuaGlucw=%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FCenter)