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)

显示结果

相关推荐
Lyyaoo.3 分钟前
【JAVA基础面经】进程间的通信方式
java·开发语言·python
小此方6 分钟前
Re:思考·重建·记录 现代C++ C++11篇 (三) 深度解构:可变参数模板、类功能演进与 STL 的新版图
开发语言·c++·stl·c++11·现代c++
小坏讲微服务10 分钟前
Claude Code 终极实战指南:从终端 Agent 到 AI+Java 开发
java·开发语言·人工智能
ch.ju11 分钟前
Java程序设计(第3版)第二章——类型转换(2)
java
爱学习的小囧12 分钟前
ESXi 8.0 vSwitch与dvSwitch(分布式交换机)核心区别
服务器·开发语言·分布式·php·虚拟化
斌味代码12 分钟前
NestJS 高并发实战:从异步到集群的完整方案
java·spring boot·spring
jarvisuni13 分钟前
JCode添加批量测试,一键同步运行6个Claude Code!
java·服务器·前端
组合缺一14 分钟前
Snack JSONPath 项目架构分析
java·架构·json·jsonpath·rfc 9535
人道领域17 分钟前
2026年Java后端热点科普:Java 26新特性+Java 21落地实战,解锁后端开发新范式
java·开发语言
这辈子谁会真的心疼你17 分钟前
如何修改照片的拍摄信息?三个实用方案分享
java·python·数码相机