一、新建一個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 /> <input
- type="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) {
- }
- }
這里就是通過文件流的方式來下載圖片的。
然后就可以自己選擇下載的地方了。