diff --git a/src/main/java/com/bonus/gs/sub/evaluate/evaluate/controller/UploadController.java b/src/main/java/com/bonus/gs/sub/evaluate/evaluate/controller/UploadController.java new file mode 100644 index 0000000..a0800fc --- /dev/null +++ b/src/main/java/com/bonus/gs/sub/evaluate/evaluate/controller/UploadController.java @@ -0,0 +1,71 @@ +package com.bonus.gs.sub.evaluate.evaluate.controller; + +import com.bonus.gs.sub.evaluate.manager.utils.AjaxRes; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; + +/** + * @Author:liang.chao + * @Date:2025/2/24 - 16:31 + */ + +@Controller +@RequestMapping("/upload") +@Slf4j +public class UploadController { + + @Value("${upload.dir}") + private String uploadDir; + + /** + * 文件上传 + * @param file + * @return + */ + @RequestMapping(path = "/file", method = RequestMethod.POST) + @ResponseBody + public AjaxRes uploadFile(@RequestParam("file") MultipartFile file) { + AjaxRes ar = new AjaxRes(); + if (file != null && !file.isEmpty()) { + // 验证文件类型 + String originalFileName = file.getOriginalFilename(); + String fileExtension = originalFileName != null && originalFileName.contains(".") + ? originalFileName.split("\\.")[originalFileName.split("\\.").length - 1] : ""; + if (!"xls".equalsIgnoreCase(fileExtension) + && !"xlsx".equalsIgnoreCase(fileExtension) + && !"doc".equalsIgnoreCase(fileExtension) + && !"docx".equalsIgnoreCase(fileExtension) + && !"jpg".equalsIgnoreCase(fileExtension) + && !"jpeg".equalsIgnoreCase(fileExtension) + && !"png".equalsIgnoreCase(fileExtension)) { + ar.setFailMsg("文件类型错误,请上传xls/xlsx/doc/docx/jpg/jpeg/png格式的文件"); + return ar; + } + } + try { + File targetDir = new File(uploadDir); + if (!targetDir.exists()) { + targetDir.mkdirs(); + } + String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename(); + File targetFile = new File(uploadDir, fileName); + file.transferTo(targetFile); + // 返回文件路径 + String pathname = targetFile.getAbsolutePath(); + ar.setSucceedMsg("文件上传成功"); + ar.setSucceed(pathname); + } catch (Exception e) { + log.error(e.toString(), e); + ar.setFailMsg("文件上传失败"); + } + return ar; + } +}