SpringMVC form表单 上传多个文件

参考 http://www.cnblogs.com/dongying/p/4388464.html
上传多张图片的后台





    
    

前台表单中的所有的name都应该是files,否则参数里的files无法获取到所有上传的文件

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestMapping;

@ResponseBody
@RequiresPermissions("weatherForecast:create")
@RequestMapping("/weatherForecast/create")		
public AjaxResponseMsg createWeatherForecast(WeatherForecast weatherForecast, HttpServletRequest request,
		HttpSession session) throws IOException {
		
    /*1.用HttpServletRequest接收前台的参数*/
	List files = null;
	
	/* 2.如果是上传文件请求,获取文件列表*/
	if (request instanceof MultipartHttpServletRequest) { 
		files = ((MultipartHttpServletRequest) request).getFiles("files"); 
	}
	String basePath = session.getServletContext().getRealPath("/");// 项目路径
    
   	/* 3.如果文件列表不为空,循环文件列表,保存文件 */
	if (files != null) {
		for (MultipartFile file : files) {
			/* 3.1保存图片 */
			String picUrl = HandleFile.saveFile(file, basePath);
			/* 3.2 其他后续操作 */
			
		} /*end for()*/
	} /*end if*/


}

如果是上传多张图片
1.使用 HttpServletRequest接收前台的参数
2.判断 这次请求是不是 上传文件请求,如果是,用request 获取文件列表
这样,即使前台没有上传文件,也不会出错

如果直接用MultipartFile[] 数组接收参数,可能会报错
org.springframework.web.multipart.MultipartException: The current request is not a multipart request

保存文件的方法HandleFile.saveFile()
http://blog.csdn.net/dreamstar613/article/details/53841438

你可能感兴趣的:(Spring,MVC,前后台交互-form)