您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關SpringMVC上傳文件FileUpload的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
具體內容如下
我是在已經搭建好的springMVC環境下,maven工程中的pom.xml所需要的jar包(其中spring上傳文件的兩個主要jar:commons-fileupload.jar和commons-io.jar):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zhihua</groupId> <artifactId>SpringMVC_FileUpload</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMVC_FileUpload Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本號 --> <spring.version>3.2.8.RELEASE</spring.version> <!-- junit版本號 --> <junit.version>4.10</junit.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- springMVC上傳文件依賴 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- 添加Spring依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!--spring單元測試依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- jstl標簽支持 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Servlet核心包 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!--JSP --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>SpringMVC_FileUpload</finalName> </build> </project>
在spring-mvc.xml中添加代碼:
<!-- springMVC上傳文件時,需要配置MultipartResolver處理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <property name="maxUploadSize" value="10485760000"></property> <property name="maxInMemorySize" value="40960"></property> </bean>
前端頁面(fileUpload.jsp)和上傳成功返回頁面(success.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>springmvc-文件上傳</title> </head> <body> <h2>采用流的方式上傳文件</h2> <form name="form1" action="<c:url value='/fileUpload/upload_01'/>" method="post" enctype="multipart/form-data"> <input type="file" name="file_01"/> <input type="submit" value="fileupload"/> </form> <br> <h2>采用multipart提供的file.transfer方法上傳文件1</h2> <form name="form2" action="<c:url value='/fileUpload/upload_02'/>" method="post" enctype="multipart/form-data"> <input type="file" name="file_02"/> <input type="submit" value="fileupload"/> </form> <br> <h2>采用multipart提供的file.transfer方法上傳文件2</h2> <form name="form2" action="<c:url value='/fileUpload/upload_03'/>" method="post" enctype="multipart/form-data"> <input type="file" name="file_03"/> <input type="submit" value="fileupload"/> </form> <br> <h2>使用spring MVC提供的方法上傳文件</h2> <form name="form2" action="<c:url value='/fileUpload/upload_spring'/>" method="post" enctype="multipart/form-data"> <input type="file" name="file_03"/> <input type="submit" value="fileupload"/> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h3>文件上傳成功!</h3> </body> </html>
controller 的代碼:
package com.zhihua.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartResolver; @Controller @RequestMapping("/fileUpload") public class FileUploadController { /** * 通過流的方式上傳文件 * @RequestParam("file") 將name=file控件得到的文件封裝成CommonsMultipartFile 對象 * <請替換成功能描述> <br> * <請替換成詳細描述> * @param file * @return * @author caizh * @since [1.0.0] * @version [1.0.0,2017年2月5日] */ @RequestMapping("/upload_01") public String fileUpload_1(@RequestParam("file_01")CommonsMultipartFile file)throws IOException { //用來檢測程序運行時間 long startTime = System.currentTimeMillis(); System.out.println("fileName:"+file.getOriginalFilename()); try{ //獲取輸出流 OutputStream os = new FileOutputStream("E:/"+new Date().getTime()+file.getOriginalFilename()); //獲取輸入流CommonsMultipartFile中可以直接得到文件的流 InputStream is = file.getInputStream(); int temp; //一個一個字節的讀取并寫入 while((temp=is.read())!=(-1)){ os.write(temp); } os.flush(); os.close(); is.close(); }catch(Exception e){ e.printStackTrace(); } long endTime = System.currentTimeMillis(); System.out.println("方法一的運行時間:"+String.valueOf(endTime-startTime)+"ms"); return "view/success"; } /** * 采用file.Transto 來保存上傳的文件 * <請替換成功能描述> <br> * <請替換成詳細描述> * @param file * @return * @throws IOException * @author caizh * @since [1.0.0] * @version [1.0.0,2017年2月5日] */ @RequestMapping("/upload_02") public String fileUpload_2(@RequestParam("file_02") CommonsMultipartFile file)throws IOException { long startTime = System.currentTimeMillis(); System.out.println("fileName:"+file.getOriginalFilename()); String path = "E:/"+new Date().getTime()+file.getOriginalFilename(); File newFile = new File(path); //通過CommonsMultipartFile 的方法直接寫文件 file.transferTo(newFile); long endTime = System.currentTimeMillis(); System.out.println("方法二的運行時間:"+String.valueOf(endTime-startTime)+"ms"); return "view/success"; } /** * 使用MultipartFile上傳文件 * <請替換成功能描述> <br> * <請替換成詳細描述> * @param file * @return * @author caizh * @since [1.0.0] * @version [1.0.0,2017年2月5日] */ @RequestMapping("/upload_03") public String fileUpload_3(@RequestParam(value="file_03",required=false)MultipartFile file, HttpServletRequest request){ String path = request.getSession().getServletContext().getRealPath("upload"); System.out.println(path); String fileName = file.getOriginalFilename(); File targetFile = new File(path,fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } //保存 try { file.transferTo(targetFile); }catch(Exception e){ e.printStackTrace(); } return "view/success"; } /** * 采用spring提供的上傳文件的方法 * <請替換成功能描述> <br> * <請替換成詳細描述> * @param request * @return * @throws IllegalStateException * @throws IOException * @author caizh * @since [1.0.0] * @version [1.0.0,2017年2月5日] */ @RequestMapping("/upload_spring") public String springUpload(HttpServletRequest request)throws IllegalStateException, IOException{ long startTime = System.currentTimeMillis(); //將當前上下文初始化給 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //檢查form中是否有enctype="multipart/form-data" if(multipartResolver.isMultipart(request)) { //將request變成多request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; //獲取multiRequest中所有的文件名 Iterator iter = multiRequest.getFileNames(); while(iter.hasNext()){ //一次遍歷所有的文件 MultipartFile file = multiRequest.getFile(iter.next().toString()); if(file!=null){ String path = "E:/springUpload"+file.getOriginalFilename(); //上傳 file.transferTo(new File(path)); } } } long endTime = System.currentTimeMillis(); System.out.println("方法三的運行時間:"+String.valueOf(endTime-startTime)+"ms"); return "view/success"; } }
關于“SpringMVC上傳文件FileUpload的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。