package com.ruzhoukj.sms.controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.charset.StandardCharsets; /** * 文件内容读取接口 * 接收一个以 .out 结尾的日志文件,将其内容转换为字符串返回 */ @RestController @RequestMapping("/api/log") public class LogFileController { /** * 处理日志文件上传并返回文件内容 * * @param file 上传的日志文件,必须以 .out 结尾 * @return 文件内容字符串 * @throws IllegalArgumentException 当文件不符合要求时抛出异常 */ @PostMapping("/read-content") public String readLogFileContent(@RequestParam("file") MultipartFile file) { // 1. 检查文件是否为空 if (file.isEmpty()) { throw new IllegalArgumentException("上传的文件不能为空"); } // 2. 验证文件扩展名是否为 .out String originalFilename = file.getOriginalFilename(); if (originalFilename == null || !originalFilename.endsWith(".out")) { throw new IllegalArgumentException("文件必须以 .out 结尾"); } try { // 3. 将文件内容转换为字符串 // 使用StandardCharsets.UTF_8确保正确的字符编码 String content = new String(file.getBytes(), StandardCharsets.UTF_8); //只取最后两万个字符 content = content.substring(Math.max(0, content.length() - 20000)); // 4. 返回文件内容 return content; } catch (IOException e) { // 5. 处理文件读取异常 throw new RuntimeException("文件读取失败: " + e.getMessage(), e); } } }