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)]

显示结果

相关推荐
Dola_Pan1 小时前
Linux文件IO(二)-文件操作使用详解
java·linux·服务器
wang_book1 小时前
Gitlab学习(007 gitlab项目操作)
java·运维·git·学习·spring·gitlab
AI原吾2 小时前
掌握Python-uinput:打造你的输入设备控制大师
开发语言·python·apython-uinput
机器视觉知识推荐、就业指导2 小时前
Qt/C++事件过滤器与控件响应重写的使用、场景的不同
开发语言·数据库·c++·qt
毕设木哥2 小时前
25届计算机专业毕设选题推荐-基于python的二手电子设备交易平台【源码+文档+讲解】
开发语言·python·计算机·django·毕业设计·课程设计·毕设
珞瑜·2 小时前
Matlab R2024B软件安装教程
开发语言·matlab
weixin_455446172 小时前
Python学习的主要知识框架
开发语言·python·学习
孤寂大仙v2 小时前
【C++】STL----list常见用法
开发语言·c++·list
蜗牛^^O^2 小时前
Docker和K8S
java·docker·kubernetes
她似晚风般温柔7893 小时前
Uniapp + Vue3 + Vite +Uview + Pinia 分商家实现购物车功能(最新附源码保姆级)
开发语言·javascript·uni-app