美文网首页
Spring Boot文件上传

Spring Boot文件上传

作者: 青柠_efca | 来源:发表于2019-04-17 20:29 被阅读0次

    三种上传方式

    • 直接上传到应用服务器
    • 上传到oss(内容存储在服务器)如 阿里云 七牛云
    • 前端将图片转成Base64编码上传(适于小容量的上传)

    pom.xml

           <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <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>
    
    

    在resources的templates目录下建两个html文件,如图所示的项目结构

    image

    application.properties配置一下上传参数

    spring.servlet.multipart.max-file-size=100MB
    spring.servlet.multipart.max-request-size=100MB
    
    

    编写UploadController,映射上传请求

    package com.springboot.fileupload.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.servlet.mvc.support.RedirectAttributes;
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    @Controller
    public class UploadController {
        private static String UPLOADED_FOLDER = "E:/temp/";
    
        @GetMapping("/")
        public String index() {
            return "upload";
        }
    
        @PostMapping("/upload")
        public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                       RedirectAttributes redirectAttributes) {
            if (file.isEmpty()) {
                redirectAttributes.addFlashAttribute("message", "请选择一个文件");
                return "redirect:upload_status";
            }
    
            try {
                byte[] bytes = file.getBytes();
                Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
                Files.write(path, bytes);
                redirectAttributes.addFlashAttribute("message",
                        "文件成功上传!" + file.getOriginalFilename());
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return "redirect:/upload_status";
        }
    
        @GetMapping("/upload_status")
        public String uploadStatus() {
            return "upload_status";
        }
    }
    
    

    upload.html文件

    <!DOCTYPE html>
    <html lang="en">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <body>
    <h1>Spring Boot 文件上传示例</h1>
    <form method="POST" action="/upload" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <br>
        <br>
        <input type="submit" value="提交"/>
    </form>
    </body>
    </html>
    
    

    upload_status.html文件

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <body>
    <h1>Spring Boot - 文件上传状态</h1>
    <div th:if="${message}">
        <h2 th:text="${message}"/>
    </div>
    </body>
    </html>
    
    

    运行启动主类,http://localhost:8080定向到了upload.html页面

    image

    选择一个本地文件,点击提交,将文件提交到了服务器指定目录,页面跳转到upload_status.html,提示上传成功

    image

    如果要把上传的路径跟着项目,如在static目录下的upload文件夹,则需要更改UploadController代码

    import org.springframework.stereotype.Controller;
    import org.springframework.util.ResourceUtils;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.servlet.mvc.support.RedirectAttributes;
    
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    @Controller
    public class UploadController {
    
        @GetMapping("/")
        public String index() {
            return "upload";
        }
    
        @PostMapping("/upload")
        public String singleFileUpload(@RequestParam("file") MultipartFile srcFile,
                                       RedirectAttributes redirectAttributes) {
            if (srcFile.isEmpty()) {
                redirectAttributes.addFlashAttribute("message", "请选择一个文件");
                return "redirect:upload_status";
            }
            try {
                File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
                if (!destFile.exists()) {
                    destFile = new File("");
                }
                System.out.println("file path:" + destFile.getAbsolutePath());
                File upload = new File(destFile.getAbsolutePath(), "static/");
                if (!upload.exists()) {
                    upload.mkdirs();
                }
                System.out.println("upload url:" + upload.getAbsolutePath());
                Path path = Paths.get(upload.getAbsolutePath() + "/" + srcFile.getOriginalFilename());
                byte[] bytes = srcFile.getBytes();
                Files.write(path, bytes);
                redirectAttributes.addFlashAttribute("message",
                        "文件成功上传!" + srcFile.getOriginalFilename());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "redirect:/upload_status";
        }
    
        @GetMapping("/upload_status")
        public String uploadStatus() {
            return "upload_status";
        }
    }
    
    

    会将文件上传到target/classes/static目录下

    相关文章

      网友评论

          本文标题:Spring Boot文件上传

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