美文网首页
SpringBoot2 - fileupload

SpringBoot2 - fileupload

作者: 深入浅出 | 来源:发表于2018-06-22 14:13 被阅读0次

    构建项目

    访问start.spring.io/
    添加Web、JSP、Servlet依赖

    1.配置pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
    
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
    
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>
    
    1. 配置application.properties
    spring.mvc.view.prefix=/WEB-INF/views/
    spring.mvc.view.suffix=.jsp
    
    1. 创建视图目录及视图文件
      /main/webapp/WEB-INF/views/index.jsp
    <%@ page contentType="text/html; charset=UTF-8" language="java"%>
    <html>
        <head>
            <title>file upload</title>
        </head>
        <body>
            单文件上传
            <br>
            <form action="/upload" method="post" enctype="multipart/form-data">
                <input type="file" name="file" />
                <input type="submit" value="上传">
            </form>
        </body>
    </html>
    

    创建控制器

    package com.gala.fileUploadDemo.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    @Controller
    public class UploadController {
    
        /**
         * 跳转到上传页面
         */
        @RequestMapping(value = "/index", method = RequestMethod.GET)
        public String index() {
            return "index";
        }
    
        /**
         * 文件上传
         */
        @RequestMapping(value = "/upload", method = RequestMethod.POST)
        @ResponseBody
        public String upload(MultipartFile file) {
            return "上传成功";
        }
    }
    

    单文件上传

    1. 修改UploadController.java的upload方法
    /**
     * 文件上传
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(HttpServletRequest request, MultipartFile file) {
        try {
            // 上传目录地址
            String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/";
            // 如果目录不存在,自动创建
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            // 上传文件名
            String fileName = file.getOriginalFilename();
            // 服务器端保存的文件对象
            File serverFile = new File(uploadDir + fileName);
            file.transferTo(serverFile);
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }
    

    启动项目,访问地址:http://127.0.0.1:8080/index

    多文件上传

    1. 修改上传界面index.jsp
    <%@ page contentType="text/html; charset=UTF-8" language="java"%>
    <html>
        <head>
            <title>file upload</title>
        </head>
        <body>
            单文件上传
            <br>
            <form action="/upload" method="post" enctype="multipart/form-data">
                <input type="file" name="file" />
                <input type="submit" value="单文件上传" />
            </form>
            
            <br><br>
            多文件上传
            <form action="/uploads" method="post" enctype="multipart/form-data">
                文件1:<input type="file" name="file" /><br>
                文件2:<input type="file" name="file" /><br>
                文件3:<input type="file" name="file" /><br>
                <input type="submit" value="多文件上传" />
            </form>
        </body>
    </html>
    
    1. 添加多文件上传方法
      修改UploadController.java,添加/uploads方法
    /**
     * 多文件上传
     */
    @RequestMapping(value = "/uploads", method = RequestMethod.POST)
    @ResponseBody
    public String uploads(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {
        try {
            // 上传目录地址
            String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload2/";
            System.out.println("uploads - uploadDir=" + uploadDir);
            // 如果目录不存在,自动创建
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
    
            // 遍历文件数组执行上传
            for (int i = 0; i < files.length; i++) {
                System.out.println("files[i]=" + files[i]);
                if (files[i] != null && files[i].getSize() > 0) {
                    excuteUpload(uploadDir, files[i]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }
    
    private void excuteUpload(String uploadDir, MultipartFile file) {
        // 文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 上传文件名
        String fileName = UUID.randomUUID() + suffix;
        // 服务器端保存的文件对象
        File serverFile = new File(uploadDir + fileName);
        try {
            file.transferTo(serverFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    启动项目,访问地址:http://127.0.0.1:8080/index

    修改上传限制

    SpringBoot上传文件时限制了我们上传文件最大容量为:1048576 bytes

    修改application.properties配置文件

    spring.servlet.multipart.max-file-size=30Mb    
    spring.servlet.multipart.max-request-size=30Mb  
    

    相关文章

      网友评论

          本文标题:SpringBoot2 - fileupload

          本文链接:https://www.haomeiwen.com/subject/hrohyftx.html