package com.custom.webui.controller; import com.custom.webui.dto.resp.FileDTO; import com.custom.webui.dto.resp.OcrResultDTO; import com.custom.webui.dto.resp.Result; import com.custom.webui.security.CurrentUser; import com.custom.webui.service.FileService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import com.custom.webui.entity.UploadFile; import com.custom.webui.exception.BusinessException; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.util.List; /** 文件上传与知识库管理接口。 */ @Slf4j @RestController @RequestMapping("/api/files") @RequiredArgsConstructor public class FileController { private final FileService fileService; /** * 上传文件。 * *

文件类型白名单与大小限制在 {@code webui.storage} 中配置, * 校验失败返回 400 而不是 500,方便前端直接提示用户。 * *

{@code autoIngest} 默认为 true:上传后立即向量化。 * 未入库的文件对检索完全无效,而「未向量化」这个状态对用户毫无意义 —— * 上传完就去提问却检索不到内容,是最容易让人困惑的场景。 * 需要批量上传几百个文件、想自己控制入库时机的场景可传 false。 * * @param chatId 绑定会话 id,不传表示公共知识库文件 * @param autoIngest 是否上传后立即向量化,默认 true */ @PostMapping("/upload") public Result upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "chatId", required = false) Long chatId, @RequestParam(value = "autoIngest", defaultValue = "true") boolean autoIngest, @RequestParam(value = "categoryId", required = false) Long categoryId) { return Result.success(fileService.upload( CurrentUser.requireUserId(), chatId, file, autoIngest, categoryId)); } /** 文件列表;传 chatId 则只返回该会话绑定的文件 */ @GetMapping public Result> list(@RequestParam(value = "chatId", required = false) Long chatId) { return Result.success(fileService.list(CurrentUser.requireUserId(), chatId)); } /** 删除文件记录、磁盘文件与对应向量集合 */ @DeleteMapping("/{id}") public Result delete(@PathVariable Long id) { fileService.delete(CurrentUser.requireUserId(), id); return Result.success(); } /** * 触发向量化入库。 * *

这是一个同步阻塞接口,大文档可能耗时数分钟。 * 前端应展示进度提示;后续可改为「提交任务 + 轮询状态」的异步模式。 */ @PostMapping("/{id}/ingest") public Result ingest(@PathVariable Long id) { return Result.success(fileService.ingest(CurrentUser.requireUserId(), id)); } /** * 图片文字识别(OCR)。 * *

用于「对话时上传图片」:先把图里的文字提取出来, * 前端再把它作为上下文随消息一起发送。走 OCR 而不是直接传图, * 是因为当前 Ollama 模型是纯文本模型,不支持图像输入。 * *

图片会同时存入 upload_file(磁盘 + 元数据), * 返回体里带 fileId,便于前端在消息里展示原图。 */ @PostMapping("/ocr") public Result recognizeImage(@RequestParam("file") MultipartFile file, @RequestParam(value = "chatId", required = false) Long chatId) { Long userId = CurrentUser.requireUserId(); // 复用上传逻辑落盘:图片也要能在「我的知识库」里看到、被引用 FileDTO stored = fileService.upload(userId, chatId, file, false, null); OcrResultDTO result = fileService.recognizeImage(userId, stored.getId()); result.setFileId(stored.getId()); result.setImageUrl("/api/files/" + stored.getId() + "/content"); return Result.success(result); } /** * 读取文件内容(目前用于在消息里展示用户上传的图片)。 * *

安全设计: *

    *
  1. 走正常鉴权,且校验文件归属(本人或管理员), * 否则「知道 id 就能下载别人文件」是典型的 IDOR 漏洞
  2. *
  3. 只允许图片类型 —— 这个端点是为了展示图片, * 不承担「下载任意上传文件」的职责,避免把敏感文档暴露出去
  4. *
  5. 响应头加 {@code Content-Disposition: inline}, * 并禁止浏览器嗅探类型,防止把非图片内容当 HTML 执行
  6. *
*/ @GetMapping("/{id}/content") public ResponseEntity content(@PathVariable Long id) { UploadFile file = fileService.requireManageableFile(CurrentUser.requireUserId(), id); String extension = file.getFilename() == null ? "" : file.getFilename().substring(file.getFilename().lastIndexOf('.') + 1).toLowerCase(); MediaType mediaType = switch (extension) { case "png" -> MediaType.IMAGE_PNG; case "jpg", "jpeg" -> MediaType.IMAGE_JPEG; case "gif" -> MediaType.IMAGE_GIF; case "webp" -> MediaType.parseMediaType("image/webp"); case "bmp" -> MediaType.parseMediaType("image/bmp"); default -> null; }; if (mediaType == null) { throw BusinessException.badRequest("该文件不是图片,无法通过此接口读取"); } Resource resource = fileService.loadAsResource(CurrentUser.requireUserId(), id); return ResponseEntity.ok() .contentType(mediaType) .header(HttpHeaders.CONTENT_DISPOSITION, "inline") .header("X-Content-Type-Options", "nosniff") .body(resource); } // ============================================================ // 全局知识库(管理员维护,全员可用) // ============================================================ /** * 管理员上传全局知识库文件。 * *

与普通 {@code /upload} 的区别:全局文件不绑定具体会话, * 入库后**任何登录用户**都能在「知识库」面板看到并绑定到自己的会话。 * *

权限在 Service 层校验({@code CurrentUser.isAdmin()}), * 非管理员调用返回 403 —— 不依赖前端隐藏按钮。 */ @PostMapping("/global/upload") public Result uploadGlobal(@RequestParam("file") MultipartFile file, @RequestParam(value = "autoIngest", defaultValue = "true") boolean autoIngest, @RequestParam(value = "categoryId", required = false) Long categoryId) { return Result.success( fileService.uploadGlobal(CurrentUser.requireUserId(), file, autoIngest, categoryId)); } /** * 列出全部全局知识库文件。 * *

**任何登录用户**都可访问 —— 普通用户需要它来发现可绑定的公共知识库。 * 返回体中带 {@code canManage} 标记,前端据此决定是否显示管理按钮。 */ @GetMapping("/global") public Result> listGlobal() { return Result.success(fileService.listGlobal()); } /** * 把文件设为全局 / 取消全局。仅管理员可操作。 * *

切换不影响集合名,因此已经绑定该知识库的会话不受影响。 */ @PostMapping("/{id}/global") public Result setGlobal(@PathVariable Long id, @RequestParam("isGlobal") boolean isGlobal) { return Result.success(fileService.setGlobal(CurrentUser.requireUserId(), id, isGlobal)); } }