溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

SpringMVC文件上傳

發(fā)布時(shí)間:2020-08-05 14:35:28 來(lái)源:網(wǎng)絡(luò) 閱讀:738 作者:武小豬 欄目:開(kāi)發(fā)技術(shù)

SpringMVC上傳文件DEMO

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

    1.編寫(xiě)jsp

    需要注意的點(diǎn):表單的method必須為post方式,負(fù)責(zé)上傳文件的表單編碼類型必須是“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>
	<h2>文件上傳</h2>
	<form action="upload" enctype="multipart/form-data" method="post">
		<table>
			<tr>
				<td>文件描述:</td>
				<td><input type="text" name="description"></td>
			</tr>
			<tr>
				<td>請(qǐng)選擇文件</td>
				<td><input type="file" name="file"/></td>
			</tr>
			<tr>
				<td>
					<input type="submit" value="上傳"/>
				</td>
			</tr>		
		</table>
	
	</form>
</body>
</html>

    2.編寫(xiě)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();
			}
			//將文件保存到目標(biāo)文件中
			file.transferTo(new File(path + File.separator + fileName));
			return "success";
		}else{
			return "error";
		}
				
		
	}
}

    3.配置springmvc-config.xml

    這里需要配置MultipartResolver。需要注意的是:請(qǐng)求的編碼格式必須和jsp中的pageEncoding屬性一致,以便正確讀取表單的內(nèi)容,默認(rèn)值為“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 可以自動(dòng)去掃描base-pack下面的包或者子包下面的java文件 -->
	<!-- 如果掃描到spring相關(guān)的注解類,將其注冊(cè)為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的前端控制器攔截所有請(qǐng)求 -->
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>


向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI