18 SSM框架-SpringMVC 实例文件上传(5)

               

  林炳文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

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
  5.     id="WebApp_ID" version="3.0">  
  6.     <!-- SpringMVC的前端控制器 -->  
  7.     <servlet>  
  8.         <servlet-name>MyDispatcher</servlet-name>  
  9.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  10.         <!-- 设置自己定义的控制器xml文件 -->  
  11.         <init-param>  
  12.             <param-name>contextConfigLocation</param-name>  
  13.             <param-value>/WEB-INF/springMVC-servlet.xml</param-value>  
  14.         </init-param>  
  15.         <load-on-startup>1</load-on-startup>  
  16.     </servlet>  
  17.     <!-- Spring MVC配置文件结束 -->  
  18.   
  19.     <!-- 拦截设置 -->  
  20.     <servlet-mapping>  
  21.         <servlet-name>MyDispatcher</servlet-name>  
  22.         <!-- 由SpringMVC拦截所有请求 -->  
  23.         <url-pattern>/</url-pattern>  
  24.     </servlet-mapping>  
  25.       
  26. </web-app>  
<?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文件

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:context="http://www.springframework.org/schema/context"  
  3.     xmlns:util="http://www.springframework.org/schema/util"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  5.      xmlns:mvc="http://www.springframework.org/schema/mvc"    
  6.     xsi:schemaLocation="    
  7.         http://www.springframework.org/schema/util   
  8.         http://www.springframework.org/schema/util/spring-util-3.0.xsd  
  9.         http://www.springframework.org/schema/mvc   
  10.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  11.         http://www.springframework.org/schema/beans         
  12.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  13.         http://www.springframework.org/schema/mvc      
  14.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  15.         http://www.springframework.org/schema/context     
  16.         http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  17.           
  18.     <!-- 把标记了@Controller注解的类转换为bean -->  
  19.     <context:component-scan base-package="com.mucfc" />  
  20.     <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->  
  21.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
  22.         p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>  
  23.             
  24.     <!-- 上传文件的设置 ,maxUploadSize=-1,表示无穷大。uploadTempDir为上传的临时目录 -->  
  25.    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"    
  26.         p:defaultEncoding="UTF-8"    
  27.         p:maxUploadSize="5400000"    
  28.         p:uploadTempDir="fileUpload/temp"    
  29.      />    
  30.   
  31. </beans>  
<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)控制器

  1. @Controller  
  2. @RequestMapping("/file")  
  3. public class FileController {  
  4.   
  5.     @RequestMapping("/toFile")  
  6.     public String toFileUpload() {  
  7.         return "fileUpload";  
  8.     }  
  9.   
  10.     @RequestMapping("/toFile2")  
  11.     public String toFileUpload2() {  
  12.         return "fileUpload2";  
  13.     }  
  14.   
  15.     /** 
  16.      * 方法一上传文件 
  17.      */  
  18.     @RequestMapping("/onefile")  
  19.     public String oneFileUpload(  
  20.             @RequestParam("file") CommonsMultipartFile file,  
  21.             HttpServletRequest request, ModelMap model) {  
  22.   
  23.         // 获得原始文件名  
  24.         String fileName = file.getOriginalFilename();  
  25.         System.out.println("原始文件名:" + fileName);  
  26.   
  27.         // 新文件名  
  28.         String newFileName = UUID.randomUUID() + fileName;  
  29.   
  30.         // 获得项目的路径  
  31.         ServletContext sc = request.getSession().getServletContext();  
  32.         // 上传位置  
  33.         String path = sc.getRealPath("/img") + "/"// 设定文件保存的目录  
  34.   
  35.         File f = new File(path);  
  36.         if (!f.exists())  
  37.             f.mkdirs();  
  38.         if (!file.isEmpty()) {  
  39.             try {  
  40.                 FileOutputStream fos = new FileOutputStream(path + newFileName);  
  41.                 InputStream in = file.getInputStream();  
  42.                 int b = 0;  
  43.                 while ((b = in.read()) != -1) {  
  44.                     fos.write(b);  
  45.                 }  
  46.                 fos.close();  
  47.                 in.close();  
  48.             } catch (Exception e) {  
  49.                 e.printStackTrace();  
  50.             }  
  51.         }  
  52.   
  53.         System.out.println("上传图片到:" + path + newFileName);  
  54.         // 保存文件地址,用于JSP页面回显  
  55.         model.addAttribute("fileUrl", path + newFileName);  
  56.         return "fileUpload";  
  57.     }  
  58.   
  59.     /** 
  60.      * 方法二上传文件,一次一张 
  61.      */  
  62.     @RequestMapping("/onefile2")  
  63.     public String oneFileUpload2(HttpServletRequest request,  
  64.             HttpServletResponse response) throws Exception {  
  65.         CommonsMultipartResolver cmr = new CommonsMultipartResolver(  
  66.                 request.getServletContext());  
  67.         if (cmr.isMultipart(request)) {  
  68.             MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);  
  69.             Iterator<String> files = mRequest.getFileNames();  
  70.             while (files.hasNext()) {  
  71.                 MultipartFile mFile = mRequest.getFile(files.next());  
  72.                 if (mFile != null) {  
  73.                     String fileName = UUID.randomUUID()  
  74.                             + mFile.getOriginalFilename();  
  75.                     String path = "d:/upload/" + fileName;  
  76.   
  77.                     File localFile = new File(path);  
  78.                     mFile.transferTo(localFile);  
  79.                     request.setAttribute("fileUrl", path);  
  80.                 }  
  81.             }  
  82.         }  
  83.         return "fileUpload";  
  84.     }  
  85. }  
@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

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  
  4. <%  
  5.     String path = request.getContextPath();  
  6.     String basePath = request.getScheme() + "://"  
  7.             + request.getServerName() + ":" + request.getServerPort()  
  8.             + path + "/";  
  9. %>  
  10. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  11. <html>  
  12. <head>  
  13. <title>用户上传图片页面</title>  
  14.  <base href="<%=basePath%>">  
  15. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  16. </head>  
  17. <body>  
  18.     <center>  
  19.         <form action="file/onefile"  
  20.             method="post" enctype="multipart/form-data">  
  21.             <input type="file" name="file" />   
  22.             <input type="submit" value="上 传" />  
  23.         </form>  
  24.         <h5>上传结果:</h5>  
  25.         <img alt="暂无图片" src="${fileUrl}" />  
  26.     </center>  
  27. </body>  
  28. </html>  
<%@ 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

表明图片已经上传到服务器

方法二:

使用文件流的方式来上传

  1. /** 
  2.  * 方法二上传文件,一次一张 
  3.  */  
  4. @RequestMapping("/onefile2")  
  5. public String oneFileUpload2(HttpServletRequest request,  
  6.         HttpServletResponse response) throws Exception {  
  7.     CommonsMultipartResolver cmr = new CommonsMultipartResolver(  
  8.             request.getServletContext());  
  9.     if (cmr.isMultipart(request)) {  
  10.         MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);  
  11.         Iterator<String> files = mRequest.getFileNames();  
  12.         while (files.hasNext()) {  
  13.             MultipartFile mFile = mRequest.getFile(files.next());  
  14.             if (mFile != null) {  
  15.                 String fileName = UUID.randomUUID()  
  16.                         + mFile.getOriginalFilename();  
  17.                 String path = "d:/upload/" + fileName;  
  18.   
  19.                 File localFile = new File(path);  
  20.                 mFile.transferTo(localFile);  
  21.                 request.setAttribute("fileUrl", path);  
  22.             }  
  23.         }  
  24.     }  
  25.     return "fileUpload";  
  26. }  
 /**  * 方法二上传文件,一次一张  */ @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"; }

  1. <center>  
  2.     <form action="file/onefile"  
  3.         method="post" enctype="multipart/form-data">  
  4.         <input type="file" name="file" />   
  5.         <input type="submit" value="上 传" />  
  6.     </form>  
  7.     <h5>上传结果:</h5>  
  8.     <img alt="暂无图片" src="${fileUrl}" />  
  9. </center>  
 <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>
中的
  1. <form action="file/onefile"  
<form action="file/onefile"
改成

  1. <form action="file/onefile2"  
<form action="file/onefile2"
输入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile

方法二指定上传到了本地E盘的upload文件夹

页面结果


四、多文件上传

(1)控制器

  1. @RequestMapping("/toFile2")  
  2. public String toFileUpload2() {  
  3.     return "fileUpload2";  
  4. }  
 @RequestMapping("/toFile2") public String toFileUpload2() {  return "fileUpload2"; }

  1. /** 
  2.  * 一次上传多张图片 
  3.  */  
  4. @RequestMapping("/threeFile")  
  5. public String threeFileUpload(  
  6.         @RequestParam("file") CommonsMultipartFile files[],  
  7.         HttpServletRequest request, ModelMap model) {  
  8.   
  9.     List<String> list = new ArrayList<String>();  
  10.     // 获得项目的路径  
  11.     ServletContext sc = request.getSession().getServletContext();  
  12.     // 上传位置  
  13.     String path = sc.getRealPath("/img") + "/"// 设定文件保存的目录  
  14.     File f = new File(path);  
  15.     if (!f.exists())  
  16.         f.mkdirs();  
  17.   
  18.     for (int i = 0; i < files.length; i++) {  
  19.         // 获得原始文件名  
  20.         String fileName = files[i].getOriginalFilename();  
  21.         System.out.println("原始文件名:" + fileName);  
  22.         // 新文件名  
  23.         String newFileName = UUID.randomUUID() + fileName;  
  24.         if (!files[i].isEmpty()) {  
  25.             try {  
  26.                 FileOutputStream fos = new FileOutputStream(path  
  27.                         + newFileName);  
  28.                 InputStream in = files[i].getInputStream();  
  29.                 int b = 0;  
  30.                 while ((b = in.read()) != -1) {  
  31.                     fos.write(b);  
  32.                 }  
  33.                 fos.close();  
  34.                 in.close();  
  35.             } catch (Exception e) {  
  36.                 e.printStackTrace();  
  37.             }  
  38.         }  
  39.         System.out.println("上传图片到:" + path + newFileName);  
  40.         list.add(path + newFileName);  
  41.   
  42.     }  
  43.     // 保存文件地址,用于JSP页面回显  
  44.     model.addAttribute("fileList", list);  
  45.     return "fileUpload2";  
  46.   
  47. }  
 /**  * 一次上传多张图片  */ @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

  1. <%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  
  4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  5. <%  
  6.     String path = request.getContextPath();  
  7.     String basePath = request.getScheme() + "://"  
  8.             + request.getServerName() + ":" + request.getServerPort()  
  9.             + path + "/";  
  10. %>  
  11. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  12. <html>  
  13. <head>  
  14. <title>用户上传图片页面</title>  
  15. <base href="<%=basePath%>">  
  16. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  17. </head>  
  18. <body>  
  19.     <center>  
  20.         <form action="file/threeFile" method="post"  
  21.             enctype="multipart/form-data">  
  22.             <input type="file" name="file" /><br /> <input type="file"  
  23.                 name="file" /><br /> <input type="file" name="file" /><br /> <input  
  24.                 type="submit" value="上 传" />  
  25.         </form>  
  26.         <h5>上传结果:</h5>  
  27.   
  28.         <c:forEach items="${fileList}" var="imagename">  
  29.                 <img alt="暂无图片" src="${imagename}" /> <br/>  
  30.         </c:forEach>  
  31.   
  32.   
  33.   
  34.     </center>  
  35. </body>  
  36. </html>  
<%@ 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>
注意这里用了
  1. </c:forEach>  
</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)控制器

  1. /** 
  2.  * 列出所有的图片 
  3.  */  
  4. @RequestMapping("/listFile")  
  5. public String listFile(HttpServletRequest request,  
  6.         HttpServletResponse response) {  
  7.     // 获取上传文件的目录  
  8.     ServletContext sc = request.getSession().getServletContext();  
  9.     // 上传位置  
  10.     String uploadFilePath = sc.getRealPath("/img") + "/"// 设定文件保存的目录  
  11.     // 存储要下载的文件名  
  12.     Map<String, String> fileNameMap = new HashMap<String, String>();  
  13.     // 递归遍历filepath目录下的所有文件和目录,将文件的文件名存储到map集合中  
  14.     listfile(new File(uploadFilePath), fileNameMap);// File既可以代表一个文件也可以代表一个目录  
  15.     // 将Map集合发送到listfile.jsp页面进行显示  
  16.     request.setAttribute("fileNameMap", fileNameMap);  
  17.     return "listFile";  
  18. }  
 /**  * 列出所有的图片  */ @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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值