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

总结

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

相关推荐
陈随易8 分钟前
VSCode v1.102发布,AI体验大幅提升
前端·后端·程序员
生无谓21 分钟前
什么是跨域,如何处理跨域
后端
咖啡啡不加糖22 分钟前
RabbitMQ 消息队列:从入门到Spring Boot实战
java·spring boot·rabbitmq
Smilejudy23 分钟前
极具特色的位置运算
后端
码出极致24 分钟前
支付线上问题复盘的“5W”框架
后端
玩代码29 分钟前
Java线程池原理概述
java·开发语言·线程池
ezl1fe32 分钟前
RAG 每日一技(三):不止文本,代码和Markdown如何优雅地分块?
后端
NE_STOP32 分钟前
SpringBoot--如何给项目添加配置属性及读取属性
java
jack_yin33 分钟前
手把手教你玩转 telegram-deepseek-bot 的 Admin 管理后台!
后端
浮游本尊34 分钟前
Java学习第8天 - Spring框架入门与依赖注入
后端