使用 Spring Boot 实现图片上传

目录

一、前言

二、项目准备

2.1、创建SpringBoot项目

2.2、项目结构

2.3、配置文件

2.4、创建控制器

2.5、创建服务

2.6创建前端界面

2.7、静态资源

三、运行项目

四、测试上传功能

总结


一、前言

在现代 web 开发中,图片上传功能是一个常见的需求。本文将介绍如何使用 Spring Boot 实现一个简单的图片上传功能,包括文件的上传、存储和展示。我们将使用 Spring Boot 的文件上传功能,并结合 Thymeleaf 作为模板引擎来构建前端界面。

二、项目准备

2.1、创建SpringBoot项目

可以使用 Spring Initializr 创建一个新的 Spring Boot 项目。选择以下依赖:

  • Spring Web
  • Thymeleaf
  • Spring Boot DevTools(可选,方便开发时热部署)

2.2、项目结构

springboot-image-upload

├── src

│ ├── main

│ │ ├── java

│ │ │ └── com

│ │ │ └── example

│ │ │ └── imageupload

│ │ │ ├── ImageUploadApplication.java

│ │ │ ├── controller

│ │ │ │ └── ImageUploadController.java

│ │ │ └── service

│ │ │ └── ImageUploadService.java

│ │ └── resources

│ │ ├── static

│ │ ├── templates

│ │ │ └── upload.html

│ │ └── application.properties

└── pom.xml

2.3、配置文件

src/main/resources/application.properties 中,添加如下配置:

java 复制代码
# 文件上传的最大大小
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB

# 上传文件的存储路径
file.upload-dir=uploads

2.4、创建控制器

com.example.imageupload.controller 包下,创建 ImageUploadController 类。

java 复制代码
package com.example.imageupload.controller;

import com.example.imageupload.service.ImageUploadService;
import org.springframework.beans.factory.annotation.Autowired;
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.util.List;

@Controller
public class ImageUploadController {

    @Autowired
    private ImageUploadService imageUploadService;

    @GetMapping("/")
    public String uploadPage(Model model) {
        List<String> uploadedImages = imageUploadService.getUploadedImages();
        model.addAttribute("uploadedImages", uploadedImages);
        return "upload";
    }

    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file, Model model) {
        if (file.isEmpty()) {
            model.addAttribute("message", "请选择一个文件进行上传");
            return "upload";
        }

        // 保存文件
        String imagePath = imageUploadService.uploadImage(file);
        model.addAttribute("message", "文件上传成功: " + imagePath);
        model.addAttribute("uploadedImages", imageUploadService.getUploadedImages());
        return "upload";
    }
}

2.5、创建服务

com.example.imageupload.service 包下,创建 ImageUploadService 类。

java 复制代码
package com.example.imageupload.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
public class ImageUploadService {

    @Value("${file.upload-dir}")
    private String uploadDir;

    public String uploadImage(MultipartFile file) {
        try {
            // 确保目录存在
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 文件保存路径
            Path filePath = Paths.get(uploadDir, file.getOriginalFilename());
            file.transferTo(filePath);

            return file.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<String> getUploadedImages() {
        List<String> images = new ArrayList<>();
        File dir = new File(uploadDir);
        if (dir.exists()) {
            for (File file : dir.listFiles()) {
                images.add(file.getName());
            }
        }
        return images;
    }
}

2.6创建前端界面

src/main/resources/templates 目录下,创建 upload.html 文件。

java 复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>图片上传</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <h1 class="mt-5">图片上传</h1>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="file">选择文件</label>
            <input type="file" class="form-control-file" id="file" name="file" required>
        </div>
        <button type="submit" class="btn btn-primary">上传</button>
    </form>

    <div th:if="${message}" class="alert alert-info mt-3">
        <p th:text="${message}"></p>
    </div>

    <h2 class="mt-5">已上传的图片</h2>
    <div class="row">
        <div class="col-md-3" th:each="image : ${uploadedImages}">
            <div class="card mb-4">
                <img th:src="@{/uploads/{image}(image=image)}" class="card-img-top" alt="图片">
                <div class="card-body">
                    <h5 class="card-title" th:text="${image}"></h5>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

2.7、静态资源

src/main/resources/static 目录下,创建 uploads 文件夹,确保上传的图片能够被访问。

三、运行项目

确保项目依赖已经正确引入,并在 IDE 中启动项目。打开浏览器,访http://localhost:8080/,你应该可以看到上传界面。

四、测试上传功能

  1. 选择一个图片文件进行上传,点击"上传"按钮。
  2. 上传成功后,页面会显示上传的消息和已上传的图片列表。

总结

通过上述步骤,我们成功实现了一个简单的图片上传功能。你可以根据自己的需求进一步扩展功能,比如增加文件类型和大小的限制、支持多文件上传、实现文件的删除功能等。希望这个示例能帮助你在项目中实现图片上传功能!

相关推荐
都叫我大帅哥29 分钟前
深入浅出 Resilience4j:Java 微服务的“免疫系统”实战指南
java·spring cloud
程序员爱钓鱼32 分钟前
Go语言实战案例-判断一个数是否为质数
后端·google·go
程序员爱钓鱼37 分钟前
Go语言实战案例-读取本地文本文件内容
后端·google·go
Cao_Shixin攻城狮3 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
Dcs5 小时前
还在用 Arrays.hashCode?Java 自己也能写出更快的版本!
java
fouryears_234177 小时前
Spring,Spring Boot 和 Spring MVC 的关系以及区别
java·spring boot·spring·mvc
阿葱(聪)8 小时前
java 在k8s中的部署流程
java·开发语言·docker·kubernetes
浮生带你学Java8 小时前
2025Java面试题及答案整理( 2025年 7 月最新版,持续更新)
java·开发语言·数据库·面试·职场和发展
板板正8 小时前
SpringAI——提示词(Prompt)、提示词模板(PromptTemplate)
java·spring boot·ai·prompt
板板正8 小时前
SpringAI——对话记忆
java·spring boot·ai