You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Spring项目,如何通过Swagger-UI与RestAPI实现图片上传?

解决方案

一、先搞定Swagger-UI配置(Gradle项目)

1. 添加Swagger依赖

在build.gradle中引入Springdoc OpenAPI依赖(替代停止维护的Springfox,更适合新手):

dependencies {
    // 保留你已有的Lombok、Spring Web等依赖
    implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
}

2. 配置application.yml

基础配置即可启动Swagger-UI,无需复杂设置:

springdoc:
  swagger-ui:
    enabled: true
    path: /swagger-ui.html  # 访问路径,默认就是这个,可自定义
  api-docs:
    enabled: true

3. 可选:自定义API信息(非必须)

如果需要给Swagger界面添加项目标题、版本等信息,新增配置类:

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("电商图片上传API")
                        .version("1.0")
                        .description("支持图片上传到在线图床并返回访问URL"));
    }
}

启动项目后,访问http://localhost:8080/swagger-ui.html就能看到Swagger界面。

二、集成在线图床并编写RestAPI

选无需注册的免费在线图床SM.MS实现上传,步骤如下:

1. 编写图床上传工具类

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@Slf4j
public class ImageBedUtil {
    // SM.MS公开上传API地址
    private static final String UPLOAD_URL = "https://sm.ms/api/v2/upload";

    public static String uploadImage(MultipartFile file) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("smfile", file.getResource());

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(UPLOAD_URL, requestEntity, Map.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                Map<String, Object> data = (Map<String, Object>) response.getBody().get("data");
                return (String) data.get("url");
            } else {
                log.error("图片上传失败: {}", response.getBody());
                return null;
            }
        } catch (Exception e) {
            log.error("上传图片出错", e);
            return null;
        }
    }
}

2. 编写图片上传接口

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ImageUploadController {

    @PostMapping("/upload/image")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择要上传的图片");
        }

        String imageUrl = ImageBedUtil.uploadImage(file);
        if (imageUrl != null) {
            return ResponseEntity.ok("图片上传成功,URL: " + imageUrl);
        } else {
            return ResponseEntity.internalServerError().body("图片上传失败,请重试");
        }
    }
}

三、测试验证

  1. 启动Spring Boot项目
  2. 打开Swagger-UI页面,找到/upload/image接口,点击Try it out
  3. 选择本地图片文件,点击Execute,即可获取返回的图片访问URL

若SM.MS无法使用,可替换为其他支持公开上传的图床API,仅需修改ImageBedUtil中的上传地址和响应解析逻辑。

内容的提问来源于stack exchange,提问作者BerkeYildirimer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:06:23