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)

显示结果

相关推荐
nice_lcj5206 分钟前
Spring 核心串讲:把 IoC、AOP、Boot、事务连成体系
java·spring boot·spring·面试·ioc·aop·体系串讲
nice_lcj52044 分钟前
Spring Boot 入门:几行配置怎么跑起来
java·spring boot·spring·面试·自动配置·起步依赖
艾莉丝努力练剑1 小时前
【AI大模型接入SDK】项目总结
java·开发语言·前端·c++·人工智能·学习·架构
Resean02231 小时前
SpringCloud 源码分析(二)Nacos 注册中心(上):服务注册流程与注册表模型
java·后端·spring·spring cloud
Evand J1 小时前
【MATLAB例程,无人机避障7】基于RRT*与人工势场法(RRT*+APF)的多无人机二维动态路径规划与避障。附下载链接
开发语言·matlab·无人机·rtt·路径规划·人工势场
布莱克6051 小时前
Objective-C 基本语法详解:从零开始掌握 iOS 开发语言
开发语言·ios·objective-c·基础·语法
码途行者2 小时前
每天10分钟学Go:第24课 通道-协程之间的传送带
开发语言·后端·golang
SimonKing2 小时前
别OCR了,都在用了OXR了,看那看那这款开源的OXR产品
java·后端·程序员
Rain的Java大神之路2 小时前
DTO、VO、PO 到底要不要拆?这场 Java 分层之争,今天一次讲透
java·后端·面试
CoderYanger3 小时前
Java EE 进阶:14.案例综合练习-博客系统(第三弹) :用户登录+强制登录
java·服务器·开发语言·数据库·spring boot·java-ee·mybatis