使用 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 中,添加如下配置:

复制代码
# 文件上传的最大大小
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 类。

复制代码
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 类。

复制代码
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 文件。

复制代码
<!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. 上传成功后,页面会显示上传的消息和已上传的图片列表。

总结

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

相关推荐
招风的黑耳22 分钟前
我用SpringBoot撸了一个智慧水务监控平台
java·spring boot·后端
大佐不会说日语~23 分钟前
Spring AI Alibaba 的 ChatClient 工具注册与 Function Calling 实践
人工智能·spring boot·python·spring·封装·spring ai
Miss_Chenzr26 分钟前
Springboot优卖电商系统s7zmj(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
程序员游老板26 分钟前
基于SpringBoot3+vue3的爱心陪诊平台
java·spring boot·毕业设计·软件工程·课程设计·信息与通信
期待のcode29 分钟前
Springboot核心构建插件
java·spring boot·后端
2501_9216494934 分钟前
如何获取美股实时行情:Python 量化交易指南
开发语言·后端·python·websocket·金融
Miss_Chenzr1 小时前
Springboot旅游景区管理系统9fu3n(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·旅游
serendipity_hky1 小时前
【SpringCloud | 第5篇】Seata分布式事务
分布式·后端·spring·spring cloud·seata·openfeign
五阿哥永琪2 小时前
Spring Boot 中自定义线程池的正确使用姿势:定义、注入与最佳实践
spring boot·后端·python
Victor3562 小时前
Netty(16)Netty的零拷贝机制是什么?它如何提高性能?
后端