基于SpringBoot的文件上传

上传方式:

  • 直接上传到应用服务器
  • 上传到css(阿里云、七牛云)
  • 前端将图片转成Base64编码上传

http://localhost:8080/

SpringBoot文件上传示例——前后端不分离

新建模块

image

1.upload.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Spring Boot文件上传页面</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>
</body>
</html>

表单 action /upload
/upload_status

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传状态显示</title>
</head>
<body>
<h2>Spring Boot的文件上传状态</h2>
<div th:if="${message}">
    <h2 th:text="${message}"></h2>
</div>
</body>
</html>

2.添加web、thymeleaf依赖

<dependencies>
        <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>

3.配置上传属性application.properties,指定上传文件大小限制等

#文件上传的配置
spring.servlet.multipart.max-file-size=100MB

4.编写Controller,通过java.nio实现稳健的上传


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;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 上传文件控制器
 * 直接上传到服务器
 *
 */
@Controller
public class UploadController {
    //指定一个临时路径作为上传目录
    //private static String UPLOAD_FOLDER = "C:\\Users\\Liuyu\\Desktop\\UPLOAD\\";

    //遇到http://localhost:8080,则跳转至upload.html页面
    @GetMapping("/")
    public String index() {
        return "upload";
    }

    @PostMapping("upload")
    public String fileUpload(@RequestParam("file")MultipartFile srcFile, RedirectAttributes redirectAttributes) {
        //前端没有选择文件,srcFile为空
        if(srcFile.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择一个文件");
            return "redirect:upload_status";
        }
        //选择了文件,开始上传操作
        try {
            //构建上传目标路径,找到了项目的target的classes目录
            File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
            if(!destFile.exists()) {
                destFile = new File("");
            }
            //输出目标文件的绝对路径
            System.out.println("file path:"+destFile.getAbsolutePath());
            //拼接子路径
            SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
            String times = sf_.format(new Date());
            File upload = new File(destFile.getAbsolutePath(), "static/"+times);
            //若目标文件夹不存在,则创建
            if(!upload.exists()) {
                upload.mkdirs();
            }
            System.out.println("完整的上传路径:"+upload.getAbsolutePath()+"/"+srcFile);
            //根据srcFile大小,准备一个字节数组
            byte[] bytes = srcFile.getBytes();
            //拼接上传路径
            //Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
            //通过项目路径,拼接上传路径
            Path path = Paths.get(upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
            //** 开始将源文件写入目标地址
            Files.write(path, bytes);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件原始名称
            String fileName = srcFile.getOriginalFilename();
// 获得文件后缀名称
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
// 生成最新的uuid文件名称
            String newFileName = uuid + "."+ suffixName;
            redirectAttributes.addFlashAttribute("message", "文件上传成功"+newFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:upload_status";
    }

    //匹配upload_status页面
    @GetMapping("upload_status")
    public String uploadStatusPage() {
        return "upload_status";
    }
}

5.运行项目,上传文件,结果

image
image

6.也可以将项目打成jar包,输入控制台命令"java -jar XXX"(XXX代表jar包名),运行成功之后在浏览器输入:http://localhost:8080,可以和第8点得到同样的结果

  • 删除 target 目录,一定要停止运行刚才在Application中的运行(否则运行失败)

  • 点击右侧Maven目录,找到upload项目的Lifecycle,依次双击 clean 和 install ,出现 "BUILD SUCCESS" 成功

    image
    image
  • 复制target目录下的 .jar 文件到任意目录

    image
  • 运行:http://localhost:8080,运行成功如下
image
  • 在jar的同级目录下会创建 static 文件夹来存放上传的文件
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 上传方式: 直接上传到应用服务器 上传到css(阿里云、七牛云) 前端将图片转成Base64编码上传 http:/...
    1只念旧的兔子阅读 3,188评论 0 8
  • 文件上传方式:1.直接上传到应用服务器(速度,容量) 2.上传到oss(内容存储服务器)(阿里云,七牛云)3.前端...
    六年的承诺阅读 5,738评论 0 4
  • 文件上传的三种方法 直接上传到应用服务器 上传到OSS(阿里云 七牛云) 前端将图片转成Base64编码上传 Sp...
    Rebirth_914阅读 5,120评论 0 16
  • 被选入微草俱乐部时,乔一帆激动的一晚上没睡。向来乖巧听话的他选择走上荣耀之路,其实是下了很大的决心的。家中父母开明...
    一朵90后阅读 1,810评论 0 1
  • 今天,我终于注册了自己的微信公众号。 受到其他战友的鼓舞,我早就想要开个自己的公众号,每日一篇,总结自己的所学,所...
    妄_念阅读 1,292评论 0 0

友情链接更多精彩内容