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)

显示结果

相关推荐
HehuaTang21 分钟前
requests 调大并对齐 limits 提升POD高负载场景下性能
java·docker·kubernetes
FreeBuf_22 分钟前
利用零宽度字符的隐形JavaScript混淆工具InvisibleJS浮出水面
开发语言·javascript·ecmascript
SuperherRo33 分钟前
JAVA攻防-Shiro专题&key利用链&CB1链分析&入口点&调用链&执行地&Class加载
java·shiro·反序列化·cb1链
lsx20240640 分钟前
Go 语言指针
开发语言
沛沛老爹41 分钟前
Web开发者转型AI:Agent Skills版本控制与管理实战——从Git到AI技能仓库
java·前端·人工智能·git·架构·rag
我命由我123451 小时前
充血模型与贫血模型
java·服务器·后端·学习·架构·java-ee·系统架构
wearegogog1231 小时前
基于MATLAB的IEEE 9节点系统潮流计算
开发语言·matlab
重学一遍1 小时前
Spring Security + JWT + Redis 的认证授权系统
java·redis·spring
分布式存储与RustFS1 小时前
RustFS在AI场景下的实测:从GPU到存储的完整加速方案
开发语言·人工智能·rust·对象存储·企业存储·rustfs·minio国产化替代
daladongba1 小时前
Spring Cloud Gateway
java·spring cloud·gateway