【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 文件

相关推荐
非 白5 分钟前
【Java分布式】Nacos注册中心
java·开发语言·nacos·注册中心
吃海鲜的骆驼11 分钟前
服务异步通讯与RabbitMQ
java·分布式·后端·rabbitmq
m0_7482336412 分钟前
RabbitMQ 进阶
android·前端·后端
羱滒14 分钟前
sql调优之数据库开发规范
java·数据库·数据库开发
m0_7482386321 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
桦说编程23 分钟前
【硬核总结】如何轻松实现只计算一次、惰性求值?良性竞争条件的广泛使用可能超过你的想象!String实际上是可变的?
后端·函数式编程
Forget the Dream43 分钟前
设计模式之责任链模式
java·c++·设计模式·责任链模式
jonyleek1 小时前
「JVS更新日志」低代码、企业会议、智能BI、智能排产2.26更新说明
java·大数据·低代码·数据分析·软件需求
计算机小白一个1 小时前
蓝桥杯 Java B 组之最短路径算法(Dijkstra、Floyd-Warshall)
java·数据结构·算法·蓝桥杯
曼岛_1 小时前
[密码学实战]Java实现SM4加解密(ecb,cbc)及工具验证
java·密码学