【SpringBoot】16 文件上传(Thymeleaf)

介绍

文件上传是指将本地的图片、视频、音频等文件上传到服务器,供其他用户浏览下载的过程,文件上传在日常项目中用的非常广泛。

实现代码

第一步:在配置文件新增如下配置

application.yml

yml 复制代码
spring:
  servlet:
    multipart:
      max-file-size: 10MB #默认为1MB    
      max-request-size: 10MB #默认为10MB
file:
  upload:
    path: F:/files/

第二步:编写文件上传页面

upload.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head lang="en">
    <meta charset="UTF-8" />
    <title>文件上传页面</title>
</head>
<body>
<h1>文件上传页面</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
    选择要上传的txt格式文件:<input type="file" name="file"><br>
    <hr>
    <input type="submit" value="提交">
</form>
</body>
</html>

第三步:编写文件上传页面和对应接口

FileController.java

java 复制代码
package com.lm.system.controller;

import com.lm.system.exception.FileException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

/**
 * @author DUHAOLIN
 * @date 2024/10/15
 */
@Controller
public class FileController {

    private final static String FILE_FORMAT_TXT = ".txt";
    @Value("${file.upload.path}")
    private String path;

    @GetMapping("uploadPage")
    public String uploadPage() {
        return "upload";
    }

    @PostMapping("upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        //校验文件
        try {
            checkFile(file);
        } catch (FileException e) {
            e.printStackTrace();
            return e.getMessage();
        }

        String filename = path + file.getOriginalFilename().replace(FILE_FORMAT_TXT, "_" + System.currentTimeMillis() + FILE_FORMAT_TXT);
        File newFile = new File(filename);
        Files.copy(file.getInputStream(), newFile.toPath());
        return "新文件已生成," + newFile.getAbsolutePath();
    }

    private void checkFile(MultipartFile file) {
        //校验文件大小
        if (file.getSize() > 10485760L) //10MB
            throw new RuntimeException("文件大于10MB");

        //校验文件名
        checkFilename(file.getOriginalFilename());
    }

    private void checkFilename(String filename) {
        if (!StringUtils.hasText(filename))
            throw new FileException("文件名有误");
        if (!filename.endsWith(FILE_FORMAT_TXT))
            throw new FileException("文件类型有误");
    }

  

}

第四步:添加文件异常类

FileException.java

java 复制代码
package com.lm.system.exception;

/**
 * @author DUHAOLIN
 * @date 2024/10/15
 */
public class FileException extends RuntimeException {
    public FileException() {
        super();
    }

    public FileException(String message) {
        super(message);
    }

    public FileException(String message, Throwable cause) {
        super(message, cause);
    }
}

效果图

上传不正确的非 .txt 格式的文件

上传确认的 .txt 文件

相关推荐
小毅&Nora15 分钟前
【Java线程安全实战】⑨ CompletableFuture的高级用法:从基础到高阶,结合虚拟线程
java·线程安全·虚拟线程
冰冰菜的扣jio15 分钟前
Redis缓存中三大问题——穿透、击穿、雪崩
java·redis·缓存
小璐猪头28 分钟前
专为 Spring Boot 设计的 Elasticsearch 日志收集 Starter
java
韩师傅29 分钟前
前端开发消亡史:AI也无法掩盖没有设计创造力的真相
前端·人工智能·后端
ps酷教程1 小时前
HttpPostRequestDecoder源码浅析
java·http·netty
闲人编程1 小时前
消息通知系统实现:构建高可用、可扩展的企业级通知服务
java·服务器·网络·python·消息队列·异步处理·分发器
栈与堆1 小时前
LeetCode-1-两数之和
java·数据结构·后端·python·算法·leetcode·rust
superman超哥1 小时前
双端迭代器(DoubleEndedIterator):Rust双向遍历的优雅实现
开发语言·后端·rust·双端迭代器·rust双向遍历
1二山似1 小时前
crmeb多商户启动swoole时报‘加密文件丢失’
后端·swoole
马卡巴卡1 小时前
Java CompletableFuture 接口与原理详解
后端