zoukankan      html  css  js  c++  java
  • Springmvc文件上传

    1、commons-fileupload-1.2.2.jar

    2、commons-io-2.0.1.jar

    2、要实现SpringMVC的文件上传,需要配置一下文件:

    复制代码
     1     <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
     2     <bean id="multipartResolver"
     3         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     4         <property name="defaultEncoding" value="UTF-8" />
     5         <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
     6         <property name="maxUploadSize" value="-1" />
     7     </bean>
     8 
     9     <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
    10     <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
    11     <bean id="exceptionResolver"
    12         class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    13         <property name="exceptionMappings">
    14             <props>
    15                 <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到XXX页面 -->
    16                 <prop
    17                     key="org.springframework.web.multipart.MaxUploadSizeExceededException">跳转XXX页面</prop>
    18             </props>
    19         </property>
    20     </bean>
    复制代码

    3、上传页面

    复制代码
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <%
     4     String path = request.getContextPath();
     5     String basePath = request.getScheme() + "://"
     6             + request.getServerName() + ":" + request.getServerPort()
     7             + path + "/";
     8 %>
     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 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    14 <title>上传文件</title>
    15 </head>
    16 <body>
    17     <form action="<%=basePath%>upload.do" method="post"
    18         enctype="multipart/form-data">
    19         <input type="hidden" name="tuzi" value="tuzi">
    20         上传文件:<input type="file" name="uploadfile">
    21          <input type="submit" value="上传">
    22     </form>
    23 </body>
    24 </html>
    复制代码

    4、文件处理类:

    复制代码
     1 package lcw.controller;
     2 
     3 import java.io.File;
     4 import java.io.IOException;
     5 
     6 import javax.servlet.http.HttpServletRequest;
     7 
     8 import org.apache.commons.io.FileUtils;
     9 import org.springframework.stereotype.Controller;
    10 import org.springframework.web.bind.annotation.RequestMapping;
    11 import org.springframework.web.bind.annotation.RequestParam;
    12 import org.springframework.web.multipart.commons.CommonsMultipartFile;
    13 
    14 /**
    15  * 
    16  * 文件上传处理类
    17  *
    18  */
    19 @Controller
    20 public class FileController {
    21 
    22     //单文件上传
    23     @RequestMapping(value = "/upload.do")
    24     public String queryFileData(
    25             @RequestParam("uploadfile") CommonsMultipartFile file,
    26             HttpServletRequest request) {
    27         // MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
    28         if (!file.isEmpty()) {
    29             String type = file.getOriginalFilename().substring(
    30                     file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
    31             String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
    32             String path = request.getSession().getServletContext()
    33                     .getRealPath("/upload/" + filename);// 存放位置
    34             File destFile = new File(path);
    35             try {
    36                 // FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
    37                 FileUtils
    38                         .copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
    39             } catch (IOException e) {
    40                 e.printStackTrace();
    41             }
    42             return "redirect:upload_ok.jsp";
    43         } else {
    44             return "redirect:upload_error.jsp";
    45         }
    46     }
    47 }
    复制代码

    5、再来看下关于多文件上传,其实原理还是一样,只不过是把CommonsMultipartFile类对象换成一个数组,然后用一个for循环去遍历这个数组,并分别存入。

    复制代码
     1 package lcw.controller;
     2 
     3 import java.io.File;
     4 import java.io.IOException;
     5 
     6 import javax.servlet.http.HttpServletRequest;
     7 
     8 import org.apache.commons.io.FileUtils;
     9 import org.springframework.stereotype.Controller;
    10 import org.springframework.web.bind.annotation.RequestMapping;
    11 import org.springframework.web.bind.annotation.RequestParam;
    12 import org.springframework.web.multipart.commons.CommonsMultipartFile;
    13 
    14 /**
    15  * 
    16  * 文件上传处理类
    17  *
    18  */
    19 @Controller
    20 public class FileController {
    21 
    22     //单文件上传
    23     @RequestMapping(value = "/upload.do")
    24     public String queryFileData(
    25             @RequestParam("uploadfile") CommonsMultipartFile file,
    26             HttpServletRequest request) {
    27         // MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
    28         if (!file.isEmpty()) {
    29             String type = file.getOriginalFilename().substring(
    30                     file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
    31             String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
    32             String path = request.getSession().getServletContext()
    33                     .getRealPath("/upload/" + filename);// 存放位置
    34             File destFile = new File(path);
    35             try {
    36                 // FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
    37                 FileUtils
    38                         .copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
    39             } catch (IOException e) {
    40                 e.printStackTrace();
    41             }
    42             return "redirect:upload_ok.jsp";
    43         } else {
    44             return "redirect:upload_error.jsp";
    45         }
    46     }
    47 
    48     //多文件上传
    49     @RequestMapping(value = "/uploads.do")
    50     public String queryFileDatas(
    51             @RequestParam("uploadfile") CommonsMultipartFile[] files,
    52             HttpServletRequest request) {
    53         if (files != null) {
    54             for (int i = 0; i < files.length; i++) {
    55                 String type = files[i].getOriginalFilename().substring(
    56                         files[i].getOriginalFilename().indexOf("."));// 取文件格式后缀名
    57                 String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
    58                 String path = request.getSession().getServletContext()
    59                         .getRealPath("/upload/" + filename);// 存放位置
    60                 File destFile = new File(path);
    61                 try {
    62                     FileUtils.copyInputStreamToFile(files[i].getInputStream(),
    63                             destFile);// 复制临时文件到指定目录下
    64                 } catch (IOException e) {
    65                     e.printStackTrace();
    66                 }
    67             }
    68             return "redirect:upload_ok.jsp";
    69         } else {
    70             return "redirect:upload_error.jsp";
    71         }
    72 
    73     }
    74 
    75 }
    复制代码
  • 相关阅读:
    高等软工第三次作业——设计也可以按图索骥
    高等软工第二次作业-从需求分析看软件开发的挑战
    高等软工第一次作业——期望与笃信
    【ACM-ICPC 2018 徐州赛区网络预赛】D.Easy Math 杜教筛
    【HDU 6428】Calculate 莫比乌斯反演+线性筛
    【BZOJ 4199】[Noi2015]品酒大会 后缀自动机+DP
    【BZOJ 3238】差异 后缀自动机+树形DP
    【Codeforces Round #466】E. Cashback DP+ST表
    【BZOJ 4709】柠檬 斜率优化dp+单调栈
    Hello Tornado
  • 原文地址:https://www.cnblogs.com/s1297-lgy/p/7456093.html
Copyright © 2011-2022 走看看