java实现文件上传和显示功能

创建一个Controller用于处理文件上传和读取操作

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 java.io.IOException;
import java.io.InputStream;

@Controller
public class FileUploadController {

    @GetMapping("/upload")
    public String showUploadForm() {
        return "upload"; // 返回上传页面
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
        if (file.isEmpty()) {
            model.addAttribute("message", "请选择要上传的文件");
            return "uploadResult"; //返回上传结果
        }

        try {
            // 获取上传文件的原始文件名
            String fileName = file.getOriginalFilename();

            // 读取上传文件的内容
            byte[] content = file.getBytes();
            String fileContent = new String(content);

            model.addAttribute("fileName", fileName);
            model.addAttribute("fileContent", fileContent);
        } catch (IOException e) {
            model.addAttribute("message", "文件处理失败: " + e.getMessage());
        }

        return "uploadResult"; //返回上传结果
    }
}

创建上传页面

src/main/resources/templates目录下创建upload.html,用于文件上传。

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <h2>文件上传</h2>
    <form action="/upload" method="POST" enctype="multipart/form-data">
        <input type="file" name="file">
        <br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

创建结果显示页面

src/main/resources/templates目录下创建uploadResult.html,用于显示上传文件的结果。

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>上传结果</title>
</head>
<body>
    <h2>上传结果</h2>
    <p>文件名: <span th:text="${fileName}"></span></p>
    <p>文件内容:</p>
    <pre><span th:text="${fileContent}"></span></pre>
</body>
</html>

浏览器访问

访问地址:http://localhost:8080/upload

选择文件-点击上传

显示结果

地址:http://localhost:8080/upload

选择文件-点击上传

外链图片转存中...(img-LVXN4BMJ-1692931342426)

显示结果

相关推荐
打死不学Java代码几秒前
PaginationInnerInterceptor使用(Mybatis-plus分页)
android·java·mybatis
南客先生2 分钟前
海量聊天消息处理:ShardingJDBC分库分表、ClickHouse冷热数据分离、ES复合查询方案、Flink实时计算与SpringCloud集成
java·clickhouse·elasticsearch·flink·springcloud·shardingjdbc
w23617346019 分钟前
Tomcat:从零理解Java Web应用的“心脏”
java·前端·tomcat
chuxinweihui12 分钟前
数据结构——二叉树,堆
c语言·开发语言·数据结构·学习·算法·链表
yuren_xia14 分钟前
示例:Spring JDBC编程式事务
java·后端·spring
陈大大陈29 分钟前
基于 C++ 的用户认证系统开发:从注册登录到Redis 缓存优化
java·linux·开发语言·数据结构·c++·算法·缓存
纪元A梦32 分钟前
华为OD机试真题——通过软盘拷贝文件(2025A卷:200分)Java/python/JavaScript/C++/C语言/GO六种最佳实现
java·javascript·c++·python·华为od·go·华为od机试题
看到我,请让我去学习38 分钟前
C语言基础(day0424)
c语言·开发语言·数据结构
studyer_domi41 分钟前
Matlab 复合模糊PID
开发语言·matlab
络742 分钟前
IDEA导入并启动若依项目步骤(SpringBoot+Vue3)
java·spring boot·mysql·vue·intellij-idea