SpringMVC單檔案上傳、多檔案上傳、檔案清單顯示、檔案下載,springmvc檔案上傳

來源:互聯網
上載者:User

SpringMVC單檔案上傳、多檔案上傳、檔案清單顯示、檔案下載,springmvc檔案上傳

  林炳文Evankaka原創作品。轉載請註明出處http://blog.csdn.net/evankaka

本文詳細講解了SpringMVC執行個體單檔案上傳、多檔案上傳、檔案清單顯示、檔案下載。

本文工程免費下載

一、建立一個Web工程,匯入相關的包

springmvc的包+commons-fileupload.jar+connom-io.jar+commons-logging,jar+jstl.jar+standard.jar

整個相關的包如下:

整個工程目錄如下:

二、配置web.xml和SpringMVC檔案

(1)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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"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"><!-- SpringMVC的前端控制器 --><servlet><servlet-name>MyDispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 設定自己定義的控制器xml檔案 --><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/springMVC-servlet.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><!-- Spring MVC設定檔結束 --><!-- 攔截設定 --><servlet-mapping><servlet-name>MyDispatcher</servlet-name><!-- 由SpringMVC攔截所有請求 --><url-pattern>/</url-pattern></servlet-mapping></web-app>
(2)springMVC-servlet.xml檔案

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="      http://www.springframework.org/schema/util     http://www.springframework.org/schema/util/spring-util-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/beans               http://www.springframework.org/schema/beans/spring-beans-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/context           http://www.springframework.org/schema/context/spring-context-3.0.xsd">        <!-- 把標記了@Controller註解的類轉換為bean --><context:component-scan base-package="com.mucfc" /><!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前尾碼 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>  <!-- 上傳檔案的設定 ,maxUploadSize=-1,表示無窮大。uploadTempDir為上傳的臨時目錄 -->   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"          p:defaultEncoding="UTF-8"          p:maxUploadSize="5400000"          p:uploadTempDir="fileUpload/temp"       />  </beans>

三、單個檔案上傳

(1)控制器

@Controller@RequestMapping("/file")public class FileController {@RequestMapping("/toFile")public String toFileUpload() {return "fileUpload";}@RequestMapping("/toFile2")public String toFileUpload2() {return "fileUpload2";}/** * 方法一上傳檔案 */@RequestMapping("/onefile")public String oneFileUpload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request, ModelMap model) {// 獲得原始檔案名String fileName = file.getOriginalFilename();System.out.println("原始檔案名:" + fileName);// 新檔案名稱String newFileName = UUID.randomUUID() + fileName;// 獲得項目的路徑ServletContext sc = request.getSession().getServletContext();// 上傳位置String path = sc.getRealPath("/img") + "/"; // 設定檔案儲存的目錄File f = new File(path);if (!f.exists())f.mkdirs();if (!file.isEmpty()) {try {FileOutputStream fos = new FileOutputStream(path + newFileName);InputStream in = file.getInputStream();int b = 0;while ((b = in.read()) != -1) {fos.write(b);}fos.close();in.close();} catch (Exception e) {e.printStackTrace();}}System.out.println("上傳圖片到:" + path + newFileName);// 儲存檔案地址,用於JSP頁面回顯model.addAttribute("fileUrl", path + newFileName);return "fileUpload";}/** * 方法二上傳檔案,一次一張 */@RequestMapping("/onefile2")public String oneFileUpload2(HttpServletRequest request,HttpServletResponse response) throws Exception {CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getServletContext());if (cmr.isMultipart(request)) {MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);Iterator<String> files = mRequest.getFileNames();while (files.hasNext()) {MultipartFile mFile = mRequest.getFile(files.next());if (mFile != null) {String fileName = UUID.randomUUID()+ mFile.getOriginalFilename();String path = "d:/upload/" + fileName;File localFile = new File(path);mFile.transferTo(localFile);request.setAttribute("fileUrl", path);}}}return "fileUpload";}}
(2)JSP,這個頁面是用來上傳又用來顯示上傳後的圖片的頁面fileUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>使用者上傳圖片頁面</title> <base href="<%=basePath%>"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body><center><form action="file/onefile"method="post" enctype="multipart/form-data"><input type="file" name="file" /> <input type="submit" value="上 傳" /></form><h5>上傳結果:</h5><img alt="暫無圖片" src="${fileUrl}" /></center></body></html>

現在運行後來看看效果,輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile


控制台輸出結果,選擇圖片後

原始檔案名:Chrysanthemum.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/4eafc28c-4baa-4018-ac06-c4a5aec88d6cChrysanthemum.jpg

圖片已被上傳,可以在JSP中顯示出來

來看看伺服器的路徑:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img

表明圖片已經上傳到伺服器

方法二:

使用檔案流的方式來上傳

/** * 方法二上傳檔案,一次一張 */@RequestMapping("/onefile2")public String oneFileUpload2(HttpServletRequest request,HttpServletResponse response) throws Exception {CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getServletContext());if (cmr.isMultipart(request)) {MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);Iterator<String> files = mRequest.getFileNames();while (files.hasNext()) {MultipartFile mFile = mRequest.getFile(files.next());if (mFile != null) {String fileName = UUID.randomUUID()+ mFile.getOriginalFilename();String path = "d:/upload/" + fileName;File localFile = new File(path);mFile.transferTo(localFile);request.setAttribute("fileUrl", path);}}}return "fileUpload";}

把

<center><form action="file/onefile"method="post" enctype="multipart/form-data"><input type="file" name="file" /> <input type="submit" value="上 傳" /></form><h5>上傳結果:</h5><img alt="暫無圖片" src="${fileUrl}" /></center>
中的
<form action="file/onefile"
改成

<form action="file/onefile2"
輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile

方法二指定上傳到了本地E盤的upload檔案夾

頁面結果


四、多檔案上傳

(1)控制器

@RequestMapping("/toFile2")public String toFileUpload2() {return "fileUpload2";}

/** * 一次上傳多張圖片 */@RequestMapping("/threeFile")public String threeFileUpload(@RequestParam("file") CommonsMultipartFile files[],HttpServletRequest request, ModelMap model) {List<String> list = new ArrayList<String>();// 獲得項目的路徑ServletContext sc = request.getSession().getServletContext();// 上傳位置String path = sc.getRealPath("/img") + "/"; // 設定檔案儲存的目錄File f = new File(path);if (!f.exists())f.mkdirs();for (int i = 0; i < files.length; i++) {// 獲得原始檔案名String fileName = files[i].getOriginalFilename();System.out.println("原始檔案名:" + fileName);// 新檔案名稱String newFileName = UUID.randomUUID() + fileName;if (!files[i].isEmpty()) {try {FileOutputStream fos = new FileOutputStream(path+ newFileName);InputStream in = files[i].getInputStream();int b = 0;while ((b = in.read()) != -1) {fos.write(b);}fos.close();in.close();} catch (Exception e) {e.printStackTrace();}}System.out.println("上傳圖片到:" + path + newFileName);list.add(path + newFileName);}// 儲存檔案地址,用於JSP頁面回顯model.addAttribute("fileList", list);return "fileUpload2";}
其實就是在單檔案上傳的方法一中來修改的,只不過弄成了個迴圈

(2)JSP顯示頁面fileUpload2.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title>使用者上傳圖片頁面</title><base href="<%=basePath%>"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head><body><center><form action="file/threeFile" method="post"enctype="multipart/form-data"><input type="file" name="file" /><br /> <input type="file"name="file" /><br /> <input type="file" name="file" /><br /> <inputtype="submit" value="上 傳" /></form><h5>上傳結果:</h5><c:forEach items="${fileList}" var="imagename"><img alt="暫無圖片" src="${imagename}" /><br/></c:forEach></center></body></html>
注意這裡用了
</c:forEach>
表單,需要jstl.jar+standard.jar

(3)運行後輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile2(注意上面是單檔案沒有後面的數字2)

選擇圖片,然後點上傳


控制台輸出結果:


圖片不清看文字 吧:

原始檔案名:Desert.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/2baccc77-43b6-4908-859d-507e86a04051Desert.jpg
原始檔案名:Hydrangeas.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/51ad04e0-82aa-4b2c-958d-f00651e9ed6bHydrangeas.jpg
原始檔案名:Jellyfish.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/dee340d8-9cc0-41ae-9959-f7fa47ff172bJellyfish.jpg

三張圖片都可以顯示出來了


來看看伺服器,這就是剛剛上傳的三張


五、上傳檔案清單顯示

(1)控制器

/** * 列出所有的圖片 */@RequestMapping("/listFile")public String listFile(HttpServletRequest request,HttpServletResponse response) {// 擷取上傳檔案的目錄ServletContext sc = request.getSession().getServletContext();// 上傳位置String uploadFilePath = sc.getRealPath("/img") + "/"; // 設定檔案儲存的目錄// 儲存要下載的檔案名稱Map<String, String> fileNameMap = new HashMap<String, String>();// 遞迴遍曆filepath目錄下的所有檔案和目錄,將檔案的檔案名稱儲存到map集合中listfile(new File(uploadFilePath), fileNameMap);// File既可以代表一個檔案也可以代表一個目錄// 將Map集合發送到listfile.jsp頁面進行顯示request.setAttribute("fileNameMap", fileNameMap);return "listFile";}
(2)JSP檔案listFile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE HTML><html>  <head>    <title>下載檔案顯示頁面</title>  </head>    <body>      <!-- 遍曆Map集合 -->    <c:forEach var="me" items="${fileNameMap}">        <c:url value="/file/downFile" var="downurl">            <c:param name="filename" value="${me.key}"></c:param>        </c:url>        ${me.value}<a href="${downurl}">下載</a>        <br/>    </c:forEach>     </body></html>

(3)運行後輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/listFile       

這些為剛剛上傳到四張圖片。


六、檔案下載

(1)控制器

@RequestMapping("/downFile")public void downFile(HttpServletRequest request,HttpServletResponse response) {System.out.println("1");// 得到要下載的檔案名稱String fileName = request.getParameter("filename");System.out.println("2");try {fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");System.out.println("3");// 擷取上傳檔案的目錄ServletContext sc = request.getSession().getServletContext();System.out.println("4");// 上傳位置String fileSaveRootPath = sc.getRealPath("/img"); System.out.println(fileSaveRootPath + "\\" + fileName);// 得到要下載的檔案File file = new File(fileSaveRootPath + "\\" + fileName);// 如果檔案不存在if (!file.exists()) {request.setAttribute("message", "您要下載的資源已被刪除!!");System.out.println("您要下載的資源已被刪除!!");return;}// 處理檔案名稱String realname = fileName.substring(fileName.indexOf("_") + 1);// 設定回應標頭,控制瀏覽器下載該檔案response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(realname, "UTF-8"));// 讀取要下載的檔案,儲存到檔案輸入資料流FileInputStream in = new FileInputStream(fileSaveRootPath + "\\" + fileName);// 建立輸出資料流OutputStream out = response.getOutputStream();// 建立緩衝區byte buffer[] = new byte[1024];int len = 0;// 迴圈將輸入資料流中的內容讀取到緩衝區當中while ((len = in.read(buffer)) > 0) {// 輸出緩衝區的內容到瀏覽器,實現檔案下載out.write(buffer, 0, len);}// 關閉檔案輸入資料流in.close();// 關閉輸出資料流out.close();} catch (Exception e) {}}

這裡就是通過檔案流的方式來下載圖片的。

然後就可以自己選擇下載的地方了。


終於講完了,花了大半天啊!

本文工程免費下載

  林炳文Evankaka原創作品。轉載請註明出處http://blog.csdn.net/evankaka

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.