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)

显示结果

相关推荐
I'm Jie4 分钟前
Gradle 的项目结构与源码集(Source Sets)详解(Kotlin DSL)
android·java·开发语言·spring boot·spring·kotlin·gradle
chilavert31827 分钟前
技术演进中的开发沉思-151 java-servlet:会话管理
java·开发语言
SheepHappy31 分钟前
MyBatis-Plus 源码阅读(一)CRUD 代码自动生成原理深度剖析
java
狂奔小菜鸡32 分钟前
Day7 | Java的流程控制详解
java·后端·编程语言
霸道流氓气质37 分钟前
Java中使用Collator实现对象List按照中文姓名属性进行A-Z的排序实现
java·开发语言·list
ttghgfhhjxkl41 分钟前
《macOS 配置 GO 语言后,如何切换不同 GO 版本?》
开发语言·macos·golang
我命由我1234541 分钟前
Android PDF 操作 - AndroidPdfViewer 弹出框显示 PDF
android·java·java-ee·pdf·android studio·android-studio·android runtime
2501_9387912242 分钟前
服务器恶意进程排查:从 top 命令定位到病毒文件删除的实战步骤
java·linux·服务器
不见长安在43 分钟前
HashMap的源码学习
java·hashmap
星光一影43 分钟前
基于Jdk17+SpringBoot3AI智慧教育平台,告别低效学习,AI精准导学 + 新架构稳跑
java·学习·mysql