1. 程式人生 > >spring MVC提交處理帶檔案和非檔案表單

spring MVC提交處理帶檔案和非檔案表單

<form action="" method="post" enctype="multipart-form-date">

  <input type="file" name="file"/>
  <input type="user.userName"/>
  <input type="user.userPassword"/>
</form>

1.匯入上傳檔案所需要的jar

2.配置web.xml


	<filter>
		<filter-name>SpringCharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>SpringCharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

3.配置spring-servler.xml配置檔案

<!-- SpringMVC上傳檔案時,需要配置MultipartResolver處理器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"/>
		<!-- 指定所上傳檔案的總大小不能超過200KB。注意maxUploadSize屬性的限制不是針對單個檔案,而是所有檔案的容量之和 -->
		<property name="maxUploadSize" value="200000"/>
	</bean>
	
	<!-- SpringMVC在超出上傳檔案限制時,會丟擲org.springframework.web.multipart.MaxUploadSizeExceededException -->
	<!-- 該異常是SpringMVC在檢查上傳的檔案資訊時丟擲來的,而且此時還沒有進入到Controller方法中 -->
	<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<!-- 遇到MaxUploadSizeExceededException異常時,自動跳轉到/WEB-INF/jsp/error_fileupload.jsp頁面 -->
				<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
			</props>
		</property>
	</bean>

4.編寫Controller

@RequestMapping(value="/add",method="RequestMethod.post")
public String addUser(User user,@RequestParam MultipartFile[] myfiles,HttpServletRequest request)
{
for(MultipartFile myfile : myfiles){
			if(myfile.isEmpty()){
				System.out.println("檔案未上傳");
			}else{
				System.out.println("檔案長度: " + myfile.getSize());
				System.out.println("檔案型別: " + myfile.getContentType());
				System.out.println("檔名稱: " + myfile.getName());
				System.out.println("檔案原名: " + myfile.getOriginalFilename());
				System.out.println("========================================");
				//如果用的是Tomcat伺服器,則檔案會上傳到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\資料夾中
				String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
				//這裡不必處理IO流關閉的問題,因為FileUtils.copyInputStreamToFile()方法內部會自動把用到的IO流關掉,我是看它的原始碼才知道的
				FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
			}
		}
		users.put(user.getUsername(), user);
		return "/user/list";
}