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

总结

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

相关推荐
m0_748233641 分钟前
RabbitMQ 进阶
android·前端·后端
羱滒3 分钟前
sql调优之数据库开发规范
java·数据库·数据库开发
m0_7482386311 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
Forget the Dream32 分钟前
设计模式之责任链模式
java·c++·设计模式·责任链模式
jonyleek35 分钟前
「JVS更新日志」低代码、企业会议、智能BI、智能排产2.26更新说明
java·大数据·低代码·数据分析·软件需求
计算机小白一个1 小时前
蓝桥杯 Java B 组之最短路径算法(Dijkstra、Floyd-Warshall)
java·数据结构·算法·蓝桥杯
曼岛_1 小时前
[密码学实战]Java实现SM4加解密(ecb,cbc)及工具验证
java·密码学
菜鸟阿达1 小时前
spring boot 2.7 + seata +微服务 降级失败问题修复
spring boot·后端·微服务
清河__1 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang
Forget the Dream1 小时前
设计模式之代理模式
java·c++·设计模式·代理模式