zoukankan      html  css  js  c++  java
  • SpringMVC上传文件总结

    如果是maven项目 需要在pom.xml文件里面引入下面两个jar包
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.1</version>
            </dependency>
    
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.0.1</version>
            </dependency>

    版本可以选择最新的版本。

    如果不是,需要手动添加jar包的话,需要导入下面两个jar包:

    1、commons-fileupload-1.2.2.jar

    2、commons-io-2.0.1.jar

    jar包引入后,我们接下来需要去配置一下配置文件,在配置文件里面加入下面内容:

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

    接下来是上传页面jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%
        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>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>上传文件</title>
    </head>
    <body>
        <form action="<%=basePath%>upload.do" method="post"
            enctype="multipart/form-data">
            上传文件:<input type="file" name="uploadfile">(如果是多文件可以继续添加多个file类型的input)
             <input type="submit" value="上传">
        </form>
    </body>
    </html>

    Java类处理file

    package lcw.controller;
    
    import java.io.File;
    import java.io.IOException;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.commons.io.FileUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    /**
     * 
     * 文件上传处理类
     *
     */
    @Controller
    public class FileController {
    
        //单文件上传
        @RequestMapping(value = "/upload.do")
        public String queryFileData(
                @RequestParam("uploadfile") CommonsMultipartFile file,
                HttpServletRequest request) {
            // MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
            if (!file.isEmpty()) {
                String type = file.getOriginalFilename().substring(
                        file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
                String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
                String path = request.getSession().getServletContext()
                        .getRealPath("/upload/" + filename);// 存放位置
                File destFile = new File(path);
                try {
                    // FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
                    FileUtils
                            .copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return "redirect:upload_ok.jsp";
            } else {
                return "redirect:upload_error.jsp";
            }
        }
    }

    如果是多文件的话,原理和上面相同,但是接收参数我们是用的CommonsMultipartFile数组

    package lcw.controller;
    
    import java.io.File;
    import java.io.IOException;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.commons.io.FileUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    /**
     * 
     * 文件上传处理类
     *
     */
    @Controller
    public class FileController {
    
        //单文件上传
        @RequestMapping(value = "/upload.do")
        public String queryFileData(
                @RequestParam("uploadfile") CommonsMultipartFile file,
                HttpServletRequest request) {
            // MultipartFile是对当前上传的文件的封装,当要同时上传多个文件时,可以给定多个MultipartFile参数(数组)
            if (!file.isEmpty()) {
                String type = file.getOriginalFilename().substring(
                        file.getOriginalFilename().indexOf("."));// 取文件格式后缀名
                String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
                String path = request.getSession().getServletContext()
                        .getRealPath("/upload/" + filename);// 存放位置
                File destFile = new File(path);
                try {
                    // FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
                    FileUtils
                            .copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return "redirect:upload_ok.jsp";
            } else {
                return "redirect:upload_error.jsp";
            }
        }
    
        //多文件上传
        @RequestMapping(value = "/uploads.do")
        public String queryFileDatas(
                @RequestParam("uploadfile") CommonsMultipartFile[] files,
                HttpServletRequest request) {
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    String type = files[i].getOriginalFilename().substring(
                            files[i].getOriginalFilename().indexOf("."));// 取文件格式后缀名
                    String filename = System.currentTimeMillis() + type;// 取当前时间戳作为文件名
                    String path = request.getSession().getServletContext()
                            .getRealPath("/upload/" + filename);// 存放位置
                    File destFile = new File(path);
                    try {
                        FileUtils.copyInputStreamToFile(files[i].getInputStream(),
                                destFile);// 复制临时文件到指定目录下
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return "redirect:upload_ok.jsp";
            } else {
                return "redirect:upload_error.jsp";
            }
    
        }
    
    }
  • 相关阅读:
    【Linux】【Services】【SaaS】Docker+kubernetes(11. 构建复杂的高可用网络)
    【Linux】【Services】【SaaS】Docker+kubernetes(10. 利用反向代理实现服务高可用)
    socketserver.py
    Python 字符中文坑
    H3C对接华为S5700s---配置链路聚合
    format使用
    python 登入接口
    python 多级菜单
    Windows 下安装MongoDB
    Gerrit 服务器安装插件
  • 原文地址:https://www.cnblogs.com/cc-java/p/6774147.html
Copyright © 2011-2022 走看看