SpringMVC文件上傳

SpringMVC上傳文件DEMO

    SpringMVC爲文件上傳提供了直接的支持,這種支持是即插即用的MultipartResolver實現的。SpringMVC使用Apache Commons FileUpload技術實現了一個MultipartResolver實現類:CommonsMultipartResolver.因此SpringMVC的文件上傳需要依賴ApacheCommons FileUpload的組件(commons-io-2.5.jar以及commons-fileupload-1.3.2.jar)。

    1.編寫jsp

    需要注意的點:表單的method必須爲post方式,負責上傳文件的表單編碼類型必須是“multipart/form-data"。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>springMVC文件上傳</title>
</head>
<body>
	<h1>文件上傳</h1>
	<form action="upload" enctype="multipart/form-data" method="post">
		<table>
			<tr>
				<td>文件描述:</td>
				<td><input type="text" name="description"></td>
			</tr>
			<tr>
				<td>請選擇文件</td>
				<td><input type="file" name="file"/></td>
			</tr>
			<tr>
				<td>
					<input type="submit" value="上傳"/>
				</td>
			</tr>		
		</table>
	
	</form>
</body>
</html>

    2.編寫Controller


package com.cn.controller;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
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;

@Controller
public class FileUploadController {
	@RequestMapping(value="uploadForm")
	public String uploadForm() {
		return "uploadForm";
	}
	@RequestMapping(value="upload",method=RequestMethod.POST)
	public String upload(HttpServletRequest request, @RequestParam("description") String description,
			@RequestParam("file") MultipartFile file) throws Exception{
		System.out.println(description);
		if(!file.isEmpty()) {
		        //上傳文件的路徑
			String path = request.getServletContext().getRealPath("/p_w_picpaths/");                       //上傳文件名
			String fileName = file.getOriginalFilename();
			File filePath = new File(path,fileName);
			if(!filePath.getParentFile().exists()) {
				filePath.getParentFile().mkdirs();
			}
			//將文件保存到目標文件中
			file.transferTo(new File(path + File.separator + fileName));
			return "success";
		}else{
			return "error";
		}
				
		
	}
}

    3.配置springmvc-config.xml

    這裏需要配置MultipartResolver。需要注意的是:請求的編碼格式必須和jsp中的pageEncoding屬性一致,以便正確讀取表單的內容,默認值爲“iso8859-1”。

<?xml version="1.0"
 encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.2.xsd
		http://www.springframework.org/schema/aop    
    	http://www.springframework.org/schema/aop/spring-aop-4.2.xsd   
    	http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
		"> 
	<!-- Spring 可以自動去掃描base-pack下面的包或者子包下面的java文件 -->
	<!-- 如果掃描到spring相關的註解類,將其註冊爲spring的bean -->
	<context:component-scan base-package="com.cn.controller" />
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/content/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>		
		</property>
	</bean>
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize">
			<value>10485760</value>
		</property>
		<property name="defaultEncoding">
			<value>UTF-8</value>		
		</property>
	
	
	</bean>
	
</beans>

    4.配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringMVCTest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 定義Spring MVC前端控制器 -->
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>/WEB-INF/springmvc-config.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <!-- 讓Spring MVC的前端控制器攔截所有請求 -->
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章