springBoot与ElementUI配合上传文件

时间:2025-03-31 08:43:43
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; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RestController public class FileUploadController { @PostMapping("/upload") public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) { Map<String, Object> result = new HashMap<>(); if (file.isEmpty()) { result.put("success", false); result.put("message", "上传的文件为空"); return result; } try { String filePath = "upload/" + file.getOriginalFilename(); File dest = new File(filePath); if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } file.transferTo(dest); result.put("success", true); result.put("message", "文件上传成功"); } catch (IOException e) { result.put("success", false); result.put("message", "文件上传失败:" + e.getMessage()); } return result; } }