首页 > 代码库 > springmvc文件上传2中方法

springmvc文件上传2中方法

基于前面文章的基础上。

一、准备

    需要的jar

   

 二、配置

  1、  spmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8" ?><beans xmlns="http://www.springframework.org/schema/beans"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:context="http://www.springframework.org/schema/context"        xmlns:mvc="http://www.springframework.org/schema/mvc"        xmlns:util="http://www.springframework.org/schema/util"         xsi:schemaLocation="          http://www.springframework.org/schema/beans          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd          http://www.springframework.org/schema/context          http://www.springframework.org/schema/context/spring-context-3.0.xsd          http://www.springframework.org/schema/mvc              http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd          http://www.springframework.org/schema/util           http://www.springframework.org/schema/util/spring-util-3.0.xsd">         <!-- 默认的注解映射的支持 ,它会自动注册DefaultAnnotationHandlerMapping 与AnnotationMethodHandlerAdapter-->     <mvc:annotation-driven />        <!-- 自动扫描注解的Controller -->	<context:component-scan base-package="com.wy.controller" />	    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />    	<!-- 映射处理器 -->	<bean id="simpleUrlMapping"		class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">		<property name="mappings">			<props>				<prop key="/fileUploadController.do">fileUploadController</prop>			</props>		</property>    </bean>    	<!-- ParameterMethodNameResolver 解析请求参数,并将它匹配Controller中的方法名 -->	<bean id="parameterMethodNameResolver"		class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">		<property name="paramName" value="http://www.mamicode.com/action" />	</bean>		<bean id="fileUploadController"		class="com.wy.controller.FileUploadController">		<property name="methodNameResolver"			ref="parameterMethodNameResolver">		</property>	</bean>		<!-- 文件上传表单的视图解析器 -->	<bean id="multipartResolver"  	    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  	    <!-- one of the properties available; the maximum file size in bytes -->  	    <property name="maxUploadSize" value="http://www.mamicode.com/204800" />      </bean>  	 </beans>          

 

2、Controller

  使用两种方式:

       一种是基于注解的,另一种传统的方式HttpServletRequest

      使用第二种方式时要注意:操作方法中对应的方法参数前两位必须是request,response对象并且都要加上,否则会出现 No request handling method with name ‘insert‘ in class  "ClassName",页面显示为404错误
这个问题出现在使用多操作控制器情况下,相关的操作方法中对应的方法参数前两位必须是request,response对象,必须要有,否则会报如上异常。

 

package com.wy.controller;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;import org.springframework.util.MultiValueMap;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.multipart.MultipartHttpServletRequest;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.multiaction.MultiActionController;@Controller@RequestMapping("/fileUploadController")public class FileUploadController extends MultiActionController {	/**	 * 1、文件上传	 * @param request	 * @param response	 * @return	 */	public ModelAndView uploadFiles(HttpServletRequest request, HttpServletResponse response) {		ModelAndView mav = new ModelAndView();		// 转型为MultipartHttpRequest		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;		// 获得上传的文件(根据前台的name名称得到上传的文件)		MultiValueMap<String, MultipartFile> multiValueMap = multipartRequest.getMultiFileMap();		List<MultipartFile> file = multiValueMap.get("clientFile");		//MultipartFile file = multipartRequest.getFile("clientFile");		if(!file.isEmpty()){			//在这里就可以对file进行处理了,可以根据自己的需求把它存到数据库或者服务器的某个文件夹			System.out.println("================="+file.get(0).getName() + file.get(0).getSize());		}		 		return mav;	}	/**	 * 	 * @param name	 * @param file	 * @param session	 * @return	 */	@RequestMapping(value="http://www.mamicode.com/uploadFile", method=RequestMethod.POST)   	public String uploadFile(@RequestParam("fileName") String fileName,   	        @RequestParam("clientFile") MultipartFile clientFile, HttpSession session){   	    if (!clientFile.isEmpty()) {	    	//在这里就可以对file进行处理了,可以根据自己的需求把它存到数据库或者服务器的某个文件夹	        System.out.println("================="+clientFile.getSize());   	    }   	    return "";   	}  }

 

 对文件的具体实现

import java.io.File;import java.io.IOException;import java.util.Iterator;import java.util.UUID;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import org.springframework.web.multipart.commons.CommonsMultipartResolver;public class AddImage {	public String upload2(HttpServletRequest request,HttpServletResponse response, String fileName) throws IllegalStateException, IOException {		//创建一个通用的多部分解析器		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());		//判断 request 是否有文件上传,即多部分请求		if(multipartResolver.isMultipart(request)){			//转换成多部分request  			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;			//取得request中的所有文件名			Iterator<String> iter = multiRequest.getFileNames();			while(iter.hasNext()){				//记录上传过程起始时的时间,用来计算上传时间				int pre = (int) System.currentTimeMillis();				//取得上传文件				MultipartFile file = multiRequest.getFile(iter.next());				if(file != null){					//取得当前上传文件的文件名称					String myFileName = file.getOriginalFilename();					//如果名称不为“”,说明该文件存在,否则说明该文件不存在					if(myFileName.trim() !=""){						System.out.println(myFileName);						//重命名上传后的文件名						fileName = UUID.randomUUID() +"+"+ file.getOriginalFilename();						//定义上传路径						String path = "F:/workspace/myproject/WebRoot/image/" + fileName;						File localFile = new File(path);						file.transferTo(localFile);					}				}				//记录上传该文件后的时间				int finaltime = (int) System.currentTimeMillis();				System.out.println(finaltime - pre);							}		}		return fileName ;	}}

 

3、试图

   upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%	String path = request.getContextPath();	String basePath = request.getScheme() + "://"			+ request.getServerName() + ":" + request.getServerPort()			+ path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>	<head>		<title>file upload test</title>	</head>	<body>		<form method="post" action="<%=path %>/fileUploadController/uploadFile" enctype="multipart/form-data">			文件名: <input type="text" name="fileName" /><br/>			       			<input type="file" name="clientFile" /><br/>			<input type="submit" value="http://www.mamicode.com/上传文件"/>		</form>	</body></html>