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

总结

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

相关推荐
爬山算法28 分钟前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
猫头虎41 分钟前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
Moment1 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte2 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
程序员侠客行2 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple3 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端
MZ_ZXD0013 小时前
springboot旅游信息管理系统-计算机毕业设计源码21675
java·c++·vue.js·spring boot·python·django·php
PP东3 小时前
Flowable学习(二)——Flowable概念学习
java·后端·学习·flowable
invicinble3 小时前
springboot的核心实现机制原理
java·spring boot·后端
前端不太难3 小时前
HarmonyOS 游戏上线前必做的 7 类极端场景测试
游戏·状态模式·harmonyos