• SpringMVC:上传与下载


    参照了网上相关代码 
    注意事项: 
    1 springmvc.xml必须配置: 
    Java代码  收藏代码
    1. <bean id="multipartResolver"  
    2.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/>         

    2 WEB-INF/lib下必加入:commons-fileupload.jar与commons-io-1.4.jar二个文件 
    3 表单属性为: enctype="multipart/form-data" 
    工程项目图片如下: 

    具体代码如下: 
    FileUploadBean.java 
    Java代码  收藏代码
    1. public class FileUploadBean {     
    2.     private byte[] file;  
    3.   
    4.     public void setFile(byte[] file) {  
    5.         this.file = file;  
    6.     }  
    7.   
    8.     public byte[] getFile() {  
    9.         return file;  
    10.     }  
    11. }  

    Java代码  收藏代码
    1. package net.liuzd.web;  
    2.   
    3. import java.io.BufferedInputStream;  
    4. import java.io.BufferedOutputStream;  
    5. import java.io.File;  
    6. import java.io.FileInputStream;  
    7. import java.io.IOException;  
    8. import java.net.BindException;  
    9. import java.util.ArrayList;  
    10.   
    11. import java.util.List;  
    12. import java.util.Map;  
    13.   
    14. import javax.servlet.http.HttpServletRequest;  
    15. import javax.servlet.http.HttpServletResponse;  
    16.   
    17. import org.springframework.stereotype.Controller;  
    18. import org.springframework.util.FileCopyUtils;  
    19. import org.springframework.web.bind.annotation.PathVariable;  
    20. import org.springframework.web.bind.annotation.RequestMapping;  
    21. import org.springframework.web.bind.annotation.RequestMethod;  
    22. import org.springframework.web.bind.annotation.RequestParam;  
    23. import org.springframework.web.multipart.MultipartFile;  
    24. import org.springframework.web.multipart.MultipartHttpServletRequest;  
    25. import org.springframework.web.multipart.commons.CommonsMultipartFile;  
    26. import org.springframework.web.servlet.ModelAndView;  
    27.   
    28. /** 
    29.  * Title: Description: Copyright: Copyright (c) 2011 
    30.  * Company:http://liuzidong.iteye.com/ Makedate:2011-5-27 下午01:52:17 
    31.  *  
    32.  * @author liuzidong 
    33.  * @version 1.0 
    34.  * @since 1.0 
    35.  *  
    36.  */  
    37. @Controller  
    38. public class FileUploadController {  
    39.   
    40.     @RequestMapping(value = "/upload", method = RequestMethod.POST)  
    41.     public ModelAndView onSubmit(HttpServletRequest request,  
    42.             HttpServletResponse response, BindException errors)  
    43.             throws Exception {  
    44.   
    45.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
    46.         CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest  
    47.                 .getFile("file");  
    48.   
    49.         String name = multipartRequest.getParameter("name");  
    50.         System.out.println("name: " + name);  
    51.         // 获得文件名:  
    52.         String realFileName = file.getOriginalFilename();  
    53.         System.out.println("获得文件名:" + realFileName);  
    54.         // 获取路径  
    55.         String ctxPath = request.getSession().getServletContext().getRealPath(  
    56.                 "/")  
    57.                 + "images/";  
    58.         // 创建文件  
    59.         File dirPath = new File(ctxPath);  
    60.         if (!dirPath.exists()) {  
    61.             dirPath.mkdir();  
    62.         }  
    63.         File uploadFile = new File(ctxPath + realFileName);  
    64.         FileCopyUtils.copy(file.getBytes(), uploadFile);  
    65.         request.setAttribute("files", loadFiles(request));  
    66.         return new ModelAndView("success");  
    67.     }  
    68.   
    69.     @RequestMapping(value = "/upload2", method = RequestMethod.POST)  
    70.     public ModelAndView onSubmit2(HttpServletRequest request,  
    71.             HttpServletResponse response, BindException errors)  
    72.             throws Exception {  
    73.   
    74.         // 转型为MultipartHttpRequest  
    75.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
    76.         // 根据前台的name名称得到上传的文件  
    77.         MultipartFile file = multipartRequest.getFile("file");  
    78.         // 获得文件名:  
    79.         String realFileName = file.getOriginalFilename();  
    80.         // 获取路径  
    81.         String ctxPath = request.getSession().getServletContext().getRealPath(  
    82.                 "/")  
    83.                 + "\\" + "images\\";  
    84.         // 创建文件  
    85.         File dirPath = new File(ctxPath);  
    86.         if (!dirPath.exists()) {  
    87.             dirPath.mkdir();  
    88.         }  
    89.         File uploadFile = new File(ctxPath + realFileName);  
    90.         FileCopyUtils.copy(file.getBytes(), uploadFile);  
    91.         request.setAttribute("files", loadFiles(request));  
    92.         return new ModelAndView("success");  
    93.     }  
    94.   
    95.     @RequestMapping(value = "/upload3", method = RequestMethod.POST)  
    96.     public String upload(@RequestParam("file")  
    97.     MultipartFile image, HttpServletRequest request) throws IOException {  
    98.   
    99.         String ctxPath = request.getSession().getServletContext().getRealPath(  
    100.                 "/")  
    101.                 + "\\" + "images\\";  
    102.         System.out.println("路径:" + ctxPath);  
    103.         File file = new File(ctxPath + "/" + image.getOriginalFilename());  
    104.         // FileCopyUtils.copy(image.getBytes(),new  
    105.         // File(ctxPath+"/"+image.getOriginalFilename()));  
    106.         try {  
    107.             image.transferTo(file); // 保存上传的文件  
    108.         } catch (IllegalStateException e) {  
    109.             e.printStackTrace();  
    110.         } catch (IOException e) {  
    111.             e.printStackTrace();  
    112.         }  
    113.         request.setAttribute("files", loadFiles(request));  
    114.         return "success";  
    115.     }  
    116.   
    117.     // 多文件上传  
    118.     @RequestMapping(value = "/upload4", method = RequestMethod.POST)  
    119.     public ModelAndView fileUpload(HttpServletRequest request,  
    120.             HttpServletResponse response, BindException errors)  
    121.             throws Exception {  
    122.   
    123.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
    124.         Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();  
    125.         String ctxPath = request.getSession().getServletContext().getRealPath(  
    126.                 "/")  
    127.                 + "\\" + "images\\";  
    128.   
    129.         File file = new File(ctxPath);  
    130.         if (!file.exists()) {  
    131.             file.mkdir();  
    132.         }  
    133.         String fileName = null;  
    134.         for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {  
    135.             // 上传文件名  
    136.             // System.out.println("key: " + entity.getKey());  
    137.             MultipartFile mf = entity.getValue();  
    138.             fileName = mf.getOriginalFilename();  
    139.             File uploadFile = new File(ctxPath + fileName);  
    140.             FileCopyUtils.copy(mf.getBytes(), uploadFile);  
    141.         }  
    142.         request.setAttribute("files", loadFiles(request));  
    143.         return new ModelAndView("success");  
    144.     }  
    145.   
    146.     // @ModelAttribute("files")//此属性用于初始类时调用,但上传文件后不能时时反应上传文件个数,不适合动态数据  
    147.     public List<String> loadFiles(HttpServletRequest request) {  
    148.         List<String> files = new ArrayList<String>();  
    149.         String ctxPath = request.getSession().getServletContext().getRealPath(  
    150.                 "/")  
    151.                 + "\\" + "images\\";  
    152.         File file = new File(ctxPath);  
    153.         if (file.exists()) {  
    154.             File[] fs = file.listFiles();  
    155.             String fname = null;  
    156.             for (File f : fs) {  
    157.                 fname = f.getName();  
    158.                 if (f.isFile()) {  
    159.                     files.add(fname);  
    160.                 }  
    161.             }  
    162.         }  
    163.         return files;  
    164.     }  
    165.   
    166.     @RequestMapping("/download/{fileName}")  
    167.     public ModelAndView download(@PathVariable("fileName")  
    168.     String fileName, HttpServletRequest request, HttpServletResponse response)  
    169.             throws Exception {  
    170.   
    171.         response.setContentType("text/html;charset=utf-8");  
    172.         request.setCharacterEncoding("UTF-8");  
    173.         java.io.BufferedInputStream bis = null;  
    174.         java.io.BufferedOutputStream bos = null;  
    175.   
    176.         String ctxPath = request.getSession().getServletContext().getRealPath(  
    177.                 "/")  
    178.                 + "\\" + "images\\";  
    179.         String downLoadPath = ctxPath + fileName;  
    180.         System.out.println(downLoadPath);  
    181.         try {  
    182.             long fileLength = new File(downLoadPath).length();  
    183.             response.setContentType("application/x-msdownload;");  
    184.             response.setHeader("Content-disposition", "attachment; filename="  
    185.                     + new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
    186.             response.setHeader("Content-Length", String.valueOf(fileLength));  
    187.             bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
    188.             bos = new BufferedOutputStream(response.getOutputStream());  
    189.             byte[] buff = new byte[2048];  
    190.             int bytesRead;  
    191.             while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
    192.                 bos.write(buff, 0, bytesRead);  
    193.             }  
    194.         } catch (Exception e) {  
    195.             e.printStackTrace();  
    196.         } finally {  
    197.             if (bis != null)  
    198.                 bis.close();  
    199.             if (bos != null)  
    200.                 bos.close();  
    201.         }  
    202.         return null;  
    203.     }  
    204. }  


    spring.xml 
    Java代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8" ?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.     xmlns:p="http://www.springframework.org/schema/p"  
    5.     xmlns:context="http://www.springframework.org/schema/context"     
    6.     xsi:schemaLocation="  
    7.         http://www.springframework.org/schema/beans   
    8.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    9.         http://www.springframework.org/schema/context   
    10.         http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    11.     <!--   
    12.         自动搜索@Controller标注的类  
    13.         用于指明系统从哪个路径下寻找controller,然后提前初始化这些对象。  
    14.     -->  
    15.     <context:component-scan base-package="net.liuzd.web" />  
    16.   
    17.     <!--  ③:对模型视图名称的解析,即在模型视图名称添加前后缀 -->  
    18.     <bean  
    19.         class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
    20.         p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />  
    21.   
    22.      
    23.     <bean id="multipartResolver"  
    24.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8">  
    25.         <property name="maxUploadSize">  
    26.             <value>104857600</value>  
    27.         </property>  
    28.         <property name="maxInMemorySize">  
    29.             <value>4096</value>  
    30.         </property>  
    31.     </bean>  
    32. </beans>  

    success.jsp 
    Java代码  收藏代码
    1. <%@ taglib  prefix="c" uri="/WEB-INF/c.tld"%>  
    2. <h1>Upload Successful</h1>  
    3.     <c:forEach var="month" items="${files}">  
    4.         <li><a href="${pageContext.request.contextPath}/download/${month}.do">${month}</a></li>  
    5.     </c:forEach>  
    6.   <hr><br>  
    7.   <a href="${pageContext.request.contextPath}/index.jsp">返回</a>  


    web.xml 
    Java代码  收藏代码
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
    5.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
    6.       
    7.     <context-param>  
    8.         <param-name>log4jConfigLocation</param-name>  
    9.         <param-value>/WEB-INF/classes/log4j.properties</param-value>  
    10.     </context-param>  
    11.   
    12.     <context-param>  
    13.         <param-name>log4jRefreshInterval</param-name>  
    14.         <param-value>60000</param-value>  
    15.     </context-param>  
    16.     <context-param>  
    17.         <param-name>log4jExposeWebAppRoot</param-name>  
    18.         <param-value>false</param-value>  
    19.     </context-param>  
    20.   
    21.     <listener>  
    22.         <listener-class>  
    23.             org.springframework.web.util.Log4jConfigListener  
    24.         </listener-class>  
    25.     </listener>  
    26.   
    27.     <filter>  
    28.         <filter-name>encodingFilter</filter-name>  
    29.         <filter-class>  
    30.             org.springframework.web.filter.CharacterEncodingFilter  
    31.         </filter-class>  
    32.         <init-param>  
    33.             <param-name>encoding</param-name>  
    34.             <param-value>UTF-8</param-value>  
    35.         </init-param>  
    36.         <init-param>  
    37.             <param-name>forceEncoding</param-name>  
    38.             <param-value>false</param-value>  
    39.         </init-param>  
    40.     </filter>  
    41.   
    42.     <filter-mapping>  
    43.         <filter-name>encodingFilter</filter-name>  
    44.         <url-pattern>*.do</url-pattern>  
    45.     </filter-mapping>  
    46.   
    47.     <filter-mapping>  
    48.         <filter-name>encodingFilter</filter-name>  
    49.         <url-pattern>*.jsp</url-pattern>  
    50.     </filter-mapping>  
    51.   
    52.     <servlet>  
    53.         <servlet-name>springmvc</servlet-name>  
    54.         <servlet-class>  
    55.             org.springframework.web.servlet.DispatcherServlet  
    56.         </servlet-class>  
    57.         <init-param>  
    58.             <param-name>contextConfigLocation</param-name>  
    59.             <param-value>classpath:springmvc.xml</param-value>  
    60.         </init-param>  
    61.         <load-on-startup>1</load-on-startup>  
    62.     </servlet>  
    63.   
    64.     <servlet-mapping>  
    65.         <servlet-name>springmvc</servlet-name>  
    66.         <url-pattern>*.do</url-pattern>  
    67.     </servlet-mapping>  
    68.     <welcome-file-list>  
    69.         <welcome-file>index.jsp</welcome-file>  
    70.     </welcome-file-list>  
    71. </web-app>  
  • 相关阅读:
    nullptr 与 null
    nullptr 与 null
    UNREFERENCED_PARAMETER 的作用
    Kali-Linux无线网络渗透测试-李亚伟-第3章-监听WiFi网络--虚拟机使用无线网卡
    探寻Linux背后的“美丽心灵”——Linux创始人Linus Torvalds访谈录
    Angular2(Beta)入门
    angular2 will be kiiled by react in the future?
    《Linux设备驱动开发详解(第3版)》(即《Linux设备驱动开发详解:基于最新的Linux 4.0内核》)前言
    Angular vs React – so which do I chose?
    2015-2016前端知识体系
  • 原文地址:https://www.cnblogs.com/chenying99/p/2539109.html
Copyright © 2020-2023  润新知