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

相关推荐
云浪4 分钟前
给 AI Agent 加上语音交互:ASR + 流式 TTS 实战
前端·人工智能·后端
卷无止境10 分钟前
当代码要上线前,谁在替你把关?——Python安全审查的方法论与实践
后端·python
水无痕simon11 分钟前
1 银行业务之个人存款业务
java
long31613 分钟前
PostgreSQL 学习资料 · 入门 / 练习 / 精通 / 扩展
java·数据结构·数据库·spring boot·sql·postgresql·数据库开发
卷无止境17 分钟前
Python Dataclasses:让类定义回归简洁的艺术
后端·python
zzzll111121 分钟前
RAG(检索增强生成)技术详解:从原理到实践
java·人工智能
Seven9724 分钟前
用300行代码带你手写简化版RPC框架
java
天丁o25 分钟前
我把一套 Flowable + Spring Boot + Vue 的 BPM 流程引擎整理开源了:从流程设计器到待办闭环
spring boot·vue·工作流引擎·flowable·bpm流程引擎·流程审批
Alex Gram42 分钟前
双机热备软件哪个好
java·系统架构·c#·keepalived·高可用·双机热备·双机热备软件
纳兰青华1 小时前
拼图大师:从“暴力尝试“到“动态规划“的拆字艺术
java·算法·动态规划