尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

Spring Boot整合AI大模型API:从零构建智能穿搭点评Web应用

Spring Boot整合AI大模型API:从零构建智能穿搭点评Web应用 最近在开发一些趣味性应用时发现很多开发者想结合AI能力做一些好玩、有创意的项目但往往卡在如何将AI模型的能力与具体的、有趣的业务场景结合以及如何设计一个完整的、可交互的前后端应用。比如想做一个能“锐评”用户穿搭的AI应用听起来很有趣但具体从哪里入手呢本文将围绕“豆包锐评穿搭”这个主题完整拆解一个集成了AI大模型能力的趣味Web应用从零到一的开发全过程。我们将使用Spring Boot构建后端服务通过调用AI模型API如DeepSeek、通义千问等实现智能穿搭点评并搭配一个简洁的前端页面完成图片上传与结果展示。无论你是想学习Spring Boot整合第三方API还是想了解一个完整小项目的架构设计这篇文章都能提供一套可复现的实操方案。1. 项目背景与核心概念1.1 什么是“AI穿搭锐评”应用“AI穿搭锐评”应用的核心功能是用户上传一张包含人物穿搭的图片后端服务调用AI大模型的视觉理解与文本生成能力对图片中的穿搭风格、颜色搭配、单品选择等进行一番幽默、犀利或专业的“点评”并将生成的评语返回给用户。这不仅仅是一个简单的图片识别它结合了计算机视觉CV识别图片中的服装、配饰等元素。自然语言处理NLP根据识别结果生成符合特定风格如“锐评”、“毒舌”、“夸夸”的连贯文本。Web应用开发构建一个可供用户交互的完整系统。1.2 技术栈选型与架构为了实现这个应用我们需要一个清晰的技术架构。一个典型的选择是前后端分离架构前端负责用户界面用于图片上传、展示和结果渲染。为了快速原型开发我们可以使用简单的HTML JavaScript或者Vue.js/React等框架。本文为简化演示将使用Thymeleaf模板引擎集成在Spring Boot中实现一个单页应用。后端作为业务逻辑的核心处理图片接收、调用AI API、管理业务流程。Spring Boot是Java生态中最流行的快速开发框架其自动配置、内嵌服务器等特性非常适合此类项目。AI模型服务这是应用的“大脑”。我们不会从头训练模型而是调用成熟的大模型API。国内可选的包括DeepSeek-Vision、通义千问VL、智谱GLM等它们都提供了强大的多模态图片文本理解能力。其他可能需要简单的文件存储如本地存储或OSS、API密钥管理等。整个数据流如下用户上传图片 - Spring Boot后端接收 - 后端将图片转换为Base64或URL - 调用AI模型API - 解析API返回的文本 - 将“锐评”结果返回前端展示。2. 环境准备与项目初始化2.1 开发环境说明在开始编码前请确保你的开发环境已就绪操作系统Windows 10/11, macOS 或 Linux (如 Ubuntu) 均可。Java开发套件JDK 8 或以上版本推荐 JDK 11 或 17本文使用 JDK 17。可通过java -version命令验证。构建工具Apache Maven 3.6 或 Gradle。本文使用 Maven 进行依赖管理。集成开发环境IDEIntelliJ IDEA (推荐)、Eclipse 或 VS Code。AI模型API你需要提前申请一个可用的多模态大模型API。本文以DeepSeek和通义千问为例你需要在其官方平台注册并获取API Key。2.2 创建Spring Boot项目使用 Spring Initializr 快速生成项目骨架这是最标准的方式。访问 start.spring.io 。按以下配置选择Project: MavenLanguage: JavaSpring Boot: 选择最新的稳定版如 3.2.xProject Metadata:Group:com.example(可自定义)Artifact:doubao-fashion-review(可自定义)Name:doubao-fashion-reviewPackaging: JarJava: 17Dependencies: 添加以下依赖Spring Web- 用于构建Web控制器和RESTful API。Thymeleaf- 用于服务端渲染HTML模板。Lombok- 简化Java Bean的代码编写可选但推荐。点击“GENERATE”下载项目压缩包并解压到你的工作目录。用IDE打开项目等待Maven自动下载依赖。你的pom.xml文件核心依赖部分应类似如下dependencies dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-thymeleaf/artifactId /dependency dependency groupIdorg.projectlombok/groupId artifactIdlombok/artifactId optionaltrue/optional /dependency dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-test/artifactId scopetest/scope /dependency /dependencies3. 核心模块设计与实现3.1 项目结构规划一个清晰的项目结构有助于维护。创建完成后你的项目目录应类似如下src/main/java/com/example/doubaofashionreview/ ├── DoubaoFashionReviewApplication.java // Spring Boot 主启动类 ├── config/ │ └── ApiConfig.java // API密钥等配置类 ├── controller/ │ └── ReviewController.java // 处理HTTP请求的控制器 ├── service/ │ ├── AiModelService.java // AI模型服务接口 │ ├── impl/ │ │ ├── DeepSeekServiceImpl.java // DeepSeek API 实现 │ │ └── QwenServiceImpl.java // 通义千问 API 实现 │ └── FileStorageService.java // 文件存储服务简易版 ├── dto/ │ ├── AiRequest.java // 调用AI API的请求体封装 │ └── AiResponse.java // AI API响应的封装 └── util/ └── ImageUtils.java // 图片处理工具类如转Base643.2 配置文件与API密钥管理将敏感的API密钥放在配置文件中而不是硬编码在代码里。Spring Boot支持application.properties或application.yml。在src/main/resources/下创建application.yml文件# 应用基础配置 server: port: 8080 # AI模型API配置 ai: model: # DeepSeek 配置 (示例请替换为你的真实Key) deepseek: api-key: sk-your-deepseek-api-key-here base-url: https://api.deepseek.com/v1/chat/completions model: deepseek-chat # 或 deepseek-v2根据API文档确认 # 通义千问配置 (示例) qwen: api-key: sk-your-qwen-api-key-here base-url: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation model: qwen-vl-max # 通义千问的多模态模型 # 文件上传配置 spring: servlet: multipart: max-file-size: 10MB max-request-size: 10MB # Thymeleaf 配置非必须默认即可 thymeleaf: cache: false # 开发时关闭缓存修改模板立即生效接下来创建一个配置类来读取这些配置// 文件路径src/main/java/com/example/doubaofashionreview/config/ApiConfig.java package com.example.doubaofashionreview.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; Configuration ConfigurationProperties(prefix ai.model) Data public class ApiConfig { private DeepSeek deepseek; private Qwen qwen; Data public static class DeepSeek { private String apiKey; private String baseUrl; private String model; } Data public static class Qwen { private String apiKey; private String baseUrl; private String model; } }使用ConfigurationProperties可以方便地将配置文件中的属性绑定到Java Bean上并通过Autowired注入使用。3.3 封装AI模型服务这是项目的核心。我们定义一个服务接口然后为不同的AI提供商提供实现。这种设计符合“开闭原则”未来切换或新增模型非常方便。首先定义请求和响应的数据传输对象DTO// 文件路径src/main/java/com/example/doubaofashionreview/dto/AiRequest.java package com.example.doubaofashionreview.dto; import lombok.Data; import java.util.List; Data public class AiRequest { private String model; private ListMessage messages; private Integer max_tokens; Data public static class Message { private String role; // user 或 system private ListContent content; Data public static class Content { private String type; // text 或 image_url private String text; // 当type为text时 private ImageUrl image_url; // 当type为image_url时 Data public static class ImageUrl { private String url; // 图片URL或Base64数据格式如data:image/jpeg;base64,xxx } } } }// 文件路径src/main/java/com/example/doubaofashionreview/dto/AiResponse.java package com.example.doubaofashionreview.dto; import lombok.Data; import java.util.List; Data public class AiResponse { private String id; private String object; private Long created; private String model; private ListChoice choices; private Usage usage; Data public static class Choice { private Integer index; private Message message; private String finish_reason; Data public static class Message { private String role; private String content; // AI返回的文本内容 } } Data public static class Usage { private Integer prompt_tokens; private Integer completion_tokens; private Integer total_tokens; } }然后定义服务接口// 文件路径src/main/java/com/example/doubaofashionreview/service/AiModelService.java package com.example.doubaofashionreview.service; public interface AiModelService { /** * 根据图片的Base64编码和提示词获取AI的穿搭点评 * param imageBase64 图片的Base64编码不含前缀 * param prompt 给AI的提示词 * return AI生成的点评文本 */ String getFashionReview(String imageBase64, String prompt); }接下来以DeepSeek为例实现该接口。我们需要使用Spring的RestTemplate或WebClient来发送HTTP请求。这里使用RestTemplate。// 文件路径src/main/java/com/example/doubaofashionreview/service/impl/DeepSeekServiceImpl.java package com.example.doubaofashionreview.service.impl; import com.example.doubaofashionreview.config.ApiConfig; import com.example.doubaofashionreview.dto.AiRequest; import com.example.doubaofashionreview.dto.AiResponse; import com.example.doubaofashionreview.service.AiModelService; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.List; Service RequiredArgsConstructor Slf4j public class DeepSeekServiceImpl implements AiModelService { private final ApiConfig apiConfig; private final RestTemplate restTemplate; private final ObjectMapper objectMapper; Override public String getFashionReview(String imageBase64, String prompt) { ApiConfig.DeepSeek config apiConfig.getDeepseek(); if (config null || config.getApiKey() null) { throw new RuntimeException(DeepSeek API配置未正确设置); } // 1. 构建请求体 AiRequest request new AiRequest(); request.setModel(config.getModel()); request.setMax_tokens(1000); // 限制生成文本长度 // 构建消息 AiRequest.Message message new AiRequest.Message(); message.setRole(user); ListAiRequest.Message.Content contents new ArrayList(); // 文本部分系统提示词 AiRequest.Message.Content textContent new AiRequest.Message.Content(); textContent.setType(text); // 这里可以设计更丰富的提示词引导AI生成“锐评”风格 String systemPrompt 你是一个时尚评论家语言风格犀利、幽默、一针见血。请对用户上传的穿搭图片进行点评。请直接输出你的点评不要加任何前缀或说明。; textContent.setText(systemPrompt prompt); contents.add(textContent); // 图片部分 AiRequest.Message.Content imageContent new AiRequest.Message.Content(); imageContent.setType(image_url); AiRequest.Message.Content.ImageUrl imageUrl new AiRequest.Message.Content.ImageUrl(); // DeepSeek等API通常要求Base64数据带上前缀 imageUrl.setUrl(data:image/jpeg;base64, imageBase64); imageContent.setImage_url(imageUrl); contents.add(imageContent); message.setContent(contents); request.setMessages(List.of(message)); // 2. 设置请求头 HttpHeaders headers new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBearerAuth(config.getApiKey()); // 使用Bearer Token认证 HttpEntityAiRequest entity new HttpEntity(request, headers); // 3. 发送请求 try { log.info(正在调用DeepSeek API...); ResponseEntityString response restTemplate.exchange( config.getBaseUrl(), HttpMethod.POST, entity, String.class ); // 4. 解析响应 if (response.getStatusCode() HttpStatus.OK) { AiResponse aiResponse objectMapper.readValue(response.getBody(), AiResponse.class); if (aiResponse.getChoices() ! null !aiResponse.getChoices().isEmpty()) { String review aiResponse.getChoices().get(0).getMessage().getContent(); log.info(AI点评生成成功长度{}, review.length()); return review.trim(); } } else { log.error(DeepSeek API调用失败状态码{}响应体{}, response.getStatusCode(), response.getBody()); } } catch (Exception e) { log.error(调用DeepSeek API时发生异常, e); throw new RuntimeException(AI服务调用失败请稍后重试, e); } return 抱歉AI点评生成失败请检查图片或稍后重试。; } }关键点解释RequiredArgsConstructorLombok注解为所有final字段生成构造函数用于依赖注入。RestTemplate需要将其配置为Spring Bean。可以在主类或一个配置类中声明。提示词工程systemPrompt是引导AI生成“锐评”风格的关键。你可以不断调整这个提示词例如“请用毒舌但友好的语气点评”、“从色彩搭配、单品选择、整体风格三个维度点评”。错误处理在生产环境中需要更精细的错误处理如重试机制、降级策略等。在DoubaoFashionReviewApplication.java中或新建一个配置类来声明RestTemplateBean// 在主启动类中添加 Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder .setConnectTimeout(Duration.ofSeconds(10)) .setReadTimeout(Duration.ofSeconds(30)) .build(); } Bean public ObjectMapper objectMapper() { return new ObjectMapper(); }3.4 文件上传与图片处理服务我们需要一个服务来处理用户上传的图片文件并将其转换为Base64编码。// 文件路径src/main/java/com/example/doubaofashionreview/service/FileStorageService.java package com.example.doubaofashionreview.service; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Base64; import java.util.UUID; Service public class FileStorageService { // 简单存储到本地临时目录生产环境应使用对象存储如OSS、S3 private final Path rootLocation Paths.get(upload-dir); public FileStorageService() { try { Files.createDirectories(rootLocation); } catch (IOException e) { throw new RuntimeException(无法创建上传目录, e); } } /** * 存储上传的文件并返回Base64编码不含前缀 */ public String storeAndConvertToBase64(MultipartFile file) throws IOException { if (file.isEmpty()) { throw new RuntimeException(上传的文件为空); } // 生成唯一文件名 String originalFilename file.getOriginalFilename(); String fileExtension ; if (originalFilename ! null originalFilename.contains(.)) { fileExtension originalFilename.substring(originalFilename.lastIndexOf(.)); } String newFilename UUID.randomUUID().toString() fileExtension; Path destinationFile this.rootLocation.resolve(Paths.get(newFilename)).normalize().toAbsolutePath(); // 简单安全校验防止路径穿越 if (!destinationFile.getParent().equals(this.rootLocation.toAbsolutePath())) { throw new RuntimeException(无法将文件存储到当前目录之外。); } // 保存文件到本地仅临时获取Base64后可选删除 Files.copy(file.getInputStream(), destinationFile); // 将文件转换为Base64字符串 byte[] fileContent Files.readAllBytes(destinationFile); String base64 Base64.getEncoder().encodeToString(fileContent); // 可选删除临时文件以节省空间 // Files.deleteIfExists(destinationFile); return base64; } }3.5 控制器层连接前后端控制器负责接收HTTP请求协调服务层并返回视图或数据。// 文件路径src/main/java/com/example/doubaofashionreview/controller/ReviewController.java package com.example.doubaofashionreview.controller; import com.example.doubaofashionreview.service.AiModelService; import com.example.doubaofashionreview.service.FileStorageService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; 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; Controller RequiredArgsConstructor Slf4j public class ReviewController { private final FileStorageService fileStorageService; private final AiModelService aiModelService; // Spring会自动注入我们实现的DeepSeekServiceImpl如果只有一个实现 /** * 首页展示上传表单 */ GetMapping(/) public String index() { return index; // 对应 src/main/resources/templates/index.html } /** * 处理图片上传和AI点评请求 */ PostMapping(/review) public String reviewFashion(RequestParam(file) MultipartFile file, RequestParam(value prompt, required false, defaultValue ) String userPrompt, Model model) { try { log.info(收到图片上传请求文件名{}大小{}字节, file.getOriginalFilename(), file.getSize()); // 1. 存储图片并获取Base64 String imageBase64 fileStorageService.storeAndConvertToBase64(file); log.info(图片已转换为Base64长度{}, imageBase64.length()); // 2. 构建给AI的最终提示词可以结合用户输入 String finalPrompt 请点评这张穿搭图片。 (userPrompt.isEmpty() ? : 用户额外要求 userPrompt); // 3. 调用AI服务获取点评 String aiReview aiModelService.getFashionReview(imageBase64, finalPrompt); log.info(AI点评内容{}, aiReview); // 4. 将结果放入Model供页面显示 model.addAttribute(review, aiReview); model.addAttribute(imageBase64, data:image/jpeg;base64, imageBase64); // 加前缀用于前端img标签显示 model.addAttribute(originalFilename, file.getOriginalFilename()); } catch (Exception e) { log.error(处理请求时发生错误, e); model.addAttribute(error, 处理失败 e.getMessage()); } return result; // 对应 src/main/resources/templates/result.html } }4. 前端页面实现使用Thymeleaf模板引擎创建两个简单的HTML页面。4.1 首页 (index.html)!-- 文件路径src/main/resources/templates/index.html -- !DOCTYPE html html langzh-CN xmlns:thhttp://www.thymeleaf.org head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 title豆包锐评穿搭 - 上传你的穿搭/title link hrefhttps://cdn.jsdelivr.net/npm/bootstrap5.1.3/dist/css/bootstrap.min.css relstylesheet style body { background-color: #f8f9fa; } .container { max-width: 600px; margin-top: 50px; } .upload-area { border: 2px dashed #007bff; border-radius: 10px; padding: 40px; text-align: center; background-color: #fff; cursor: pointer; margin-bottom: 20px; } .upload-area:hover { background-color: #f0f8ff; } #preview { max-width: 100%; max-height: 300px; margin-top: 15px; } /style /head body div classcontainer h1 classtext-center mb-4 豆包锐评穿搭/h1 p classtext-muted text-center mb-4上传你的穿搭照片让AI给你来一段犀利又幽默的时尚点评/p form th:action{/review} methodpost enctypemultipart/form-data !-- 文件上传区域 -- div classupload-area onclickdocument.getElementById(fileInput).click() input typefile idfileInput namefile acceptimage/* styledisplay: none; onchangepreviewImage(event) required i classbi bi-cloud-arrow-up stylefont-size: 3rem; color: #6c757d;/i h5点击或拖拽上传图片/h5 p classtext-muted支持 JPG, PNG 格式大小不超过10MB/p /div !-- 图片预览 -- div classtext-center img idpreview classimg-thumbnail alt图片预览 styledisplay: none; /div !-- 自定义提示词可选 -- div classmb-3 label forprompt classform-label 给AI一点提示可选/label textarea classform-control idprompt nameprompt rows2 placeholder例如请重点点评一下颜色搭配 / 用毒舌一点的语气/textarea /div !-- 提交按钮 -- div classd-grid gap-2 button typesubmit classbtn btn-primary btn-lg i classbi bi-stars/i 开始锐评 /button /div /form div classmt-5 text-center text-muted small p本应用基于Spring Boot与AI大模型如DeepSeek构建图片仅用于AI分析不会存储。/p /div /div script function previewImage(event) { const reader new FileReader(); reader.onload function() { const output document.getElementById(preview); output.src reader.result; output.style.display block; }; reader.readAsDataURL(event.target.files[0]); } /script !-- Bootstrap Icons -- link relstylesheet hrefhttps://cdn.jsdelivr.net/npm/bootstrap-icons1.8.1/font/bootstrap-icons.css /body /html4.2 结果页 (result.html)!-- 文件路径src/main/resources/templates/result.html -- !DOCTYPE html html langzh-CN xmlns:thhttp://www.thymeleaf.org head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 title豆包锐评结果/title link hrefhttps://cdn.jsdelivr.net/npm/bootstrap5.1.3/dist/css/bootstrap.min.css relstylesheet style body { background-color: #f8f9fa; } .review-card { background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); border-left: 5px solid #007bff; } .quote-icon { font-size: 2rem; color: #6c757d; opacity: 0.5; } /style /head body div classcontainer py-5 div classtext-center mb-4 a href/ classbtn btn-outline-secondary mb-3i classbi bi-arrow-left/i 再评一张/a h2 AI穿搭锐评结果/h2 p classtext-muted原文件span th:text${originalFilename}/span/p /div div classrow !-- 图片展示 -- div classcol-md-5 mb-4 div classcard div classcard-header 你上传的穿搭/div div classcard-body text-center img th:src${imageBase64} classimg-fluid rounded alt上传的穿搭图片 /div /div /div !-- AI点评 -- div classcol-md-7 mb-4 div classcard review-card div classcard-header bg-primary text-white i classbi bi-chat-quote/i 豆包锐评 /div div classcard-body div classmb-3 i classbi bi-quote quote-icon/i /div !-- 显示错误或结果 -- div th:if${error} classalert alert-danger th:text${error}/div div th:if${review} classfs-5 stylewhite-space: pre-line; th:text${review}/div div classmt-3 text-end i classbi bi-quote quote-icon styletransform: rotate(180deg);/i /div /div div classcard-footer text-muted text-center smallPowered by AI • 仅供娱乐/small /div /div /div /div div classalert alert-info mt-4 h5i classbi bi-lightbulb/i 提示/h5 ul classmb-0 liAI的点评基于其对图片的理解和预设的“锐评”风格生成可能不完全准确或存在偏见请理性看待。/li li尝试上传不同风格休闲、通勤、运动的图片看看AI如何评价。/li li你可以在上传时输入提示词引导AI的点评方向。/li /ul /div /div !-- Bootstrap Icons -- link relstylesheet hrefhttps://cdn.jsdelivr.net/npm/bootstrap-icons1.8.1/font/bootstrap-icons.css /body /html5. 运行与测试5.1 启动应用确保application.yml中的API Key已替换为你自己的。在IDE中找到DoubaoFashionReviewApplication.java右键运行main方法。控制台看到Started DoubaoFashionReviewApplication in x.xxx seconds即表示启动成功。5.2 功能测试打开浏览器访问http://localhost:8080。点击上传区域选择一张包含人物穿搭的图片确保人物和服装清晰可见。可选在文本框中输入一些提示词如“请用夸张的语气夸奖”。点击“开始锐评”按钮。等待几秒取决于AI API的响应速度页面将跳转到结果页展示上传的图片和AI生成的“锐评”文本。预期效果AI会根据图片内容生成一段类似“这位同学的穿搭可谓是……”、“这套搭配在色彩上大胆地运用了……但不得不说……”这样风格鲜明的点评。6. 常见问题与排查思路在开发和使用过程中你可能会遇到以下问题问题现象可能原因排查与解决思路应用启动失败端口被占用8080端口已被其他程序使用1. 在application.yml中修改server.port。2. 使用命令netstat -ano | findstr :8080(Windows) 或lsof -i :8080(Mac/Linux) 查找并终止占用进程。上传图片后页面报错或白屏1. API Key 未配置或错误。2. 图片格式或大小问题。3. AI服务端异常或网络超时。1.检查控制台日志查看具体的异常堆栈信息。2. 确认application.yml中的api-key和base-url正确无误。3. 尝试上传更小尺寸如1MB的JPG图片测试。4. 直接在Postman等工具中调用AI API验证Key和接口是否正常。AI返回的点评内容不理想太普通、不“锐”提示词Prompt不够精准。1. 修改DeepSeekServiceImpl中的systemPrompt变量使其更具体。例如“你是一个言辞犀利、幽默风趣的时尚评论家擅长发现穿搭中的亮点和槽点。请用一段不超过200字的话点评要求语气活泼带点调侃但不要人身攻击。”2. 可以尝试让用户在前端选择点评风格如“毒舌”、“夸夸”、“专业”后端根据选择动态拼接不同的系统提示词。响应速度很慢1. 图片太大Base64编码后字符串很长导致网络传输和AI处理慢。2. AI API本身响应慢。1. 在服务端对图片进行压缩和缩放例如使用Thumbnails库将图片限制在1024px宽度以内。2. 在前端上传前就用JavaScript压缩图片。3. 为调用AI的请求设置合理的超时时间已在RestTemplate中配置并考虑前端添加加载动画。无法显示图片预览或结果页图片图片Base64编码格式问题或前端img标签的src格式错误。1. 确保ImageUtils或FileStorageService生成的Base64字符串是纯编码没有换行符。2. 结果页中img标签的src属性必须是data:image/[格式];base64,[编码]的完整格式。检查ReviewController中拼接前缀的逻辑。UnsatisfiedDependencyException启动错误Spring Bean注入失败。1. 检查AiModelService接口是否有实现类并被Service注解。2. 检查RestTemplate和ObjectMapper的Bean是否正确定义。3. 使用Autowired或构造器注入时确保依赖的Bean存在。7. 最佳实践与扩展方向7.1 工程化建议配置中心化将API Key等敏感信息移至环境变量或专业的配置中心如Apollo避免硬编码在代码或配置文件中。服务降级与熔断使用 Resilience4j 或 Sentinel 为AI服务调用添加熔断机制。当AI服务不可用或超时时可以返回一个预设的、有趣的默认评语保证应用基本可用。异步处理图片上传和AI分析可能耗时较长。可以将reviewFashion方法改为异步使用Async立即返回一个“任务ID”前端通过轮询或WebSocket来获取处理结果提升用户体验。对象存储生产环境不应将图片存储在应用服务器的本地磁盘。应集成阿里云OSS、腾讯云COS等对象存储服务上传后获取图片URL再将URL传递给AI API如果API支持。输入验证与清理对用户上传的文件进行严格的类型和大小验证。对用户输入的prompt进行基本的清理防止注入攻击虽然在此场景下风险较低。日志与监控记录详细的日志包括用户操作、AI调用耗时、成功/失败状态。这有助于排查问题和分析使用情况。7.2 功能扩展思路多模型支持与负载均衡实现QwenServiceImpl等其他AI模型的服务类。可以设计一个简单的路由策略根据配置或随机选择使用哪个模型或者在前端让用户选择“点评风格”对应不同的模型/提示词。点评历史与分享引入数据库如MySQL为用户存储点评历史。生成一个唯一的分享链接让用户可以将有趣的“锐评”结果分享到社交媒体。更丰富的提示词模板建立一个提示词模板库例如“职场穿搭指南”、“约会穿搭建议”、“复古风点评”等让用户选择使点评更具针对性。前端美化与交互使用Vue.js或React重构前端实现更流畅的单页应用体验比如拖拽上传、实时预览、点评生成时的打字机效果等。部署上线将应用打包为Jar文件部署到云服务器如阿里云ECS或容器平台如Docker Kubernetes。配置Nginx作为反向代理并申请域名。通过这个“豆包锐评穿搭”项目的完整实践你不仅学会了如何将Spring Boot与第三方AI API进行集成更掌握了一个小型Web应用从需求分析、技术选型、模块设计、编码实现到测试部署的完整流程。这种将前沿AI能力与经典后端开发结合的模式是当前很多创新应用的典型架构希望这个项目能成为你探索更多可能性的起点。
返回列表