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)

显示结果

相关推荐
不要em0啦4 分钟前
从0开始学python:简单的练习题4
开发语言·python
我想吃余5 分钟前
【C++篇】C++11:线程库
开发语言·c++
小李云雾7 分钟前
Python 多任务编程入门:进程的创建、同步与进程池使用
开发语言·数据库·python·oracle
05大叔10 分钟前
MybatisPlus
java·服务器·前端
henreash15 分钟前
C#调用F#的MailboxProcessor
开发语言·c#
CSDN_RTKLIB15 分钟前
【静态初始化与动态初始化】术语对比
开发语言·c++
天上飞的粉红小猪41 分钟前
线程同步与互斥
linux·开发语言·c++
未来之窗软件服务42 分钟前
幽冥大陆(八十九 ) 自动化在线打包任意平台软件 —东方仙盟练气期
开发语言·c#·自动化·仙盟创梦ide·东方仙盟·在线打包
Rysxt_1 小时前
鸿蒙开发语言ArkTS:全面解析优缺点与未来前景
开发语言·华为·harmonyos
java1234_小锋1 小时前
RocketMQ的Producer是如何发送消息的?
java·rocketmq·java-rocketmq