Spring boot Sencha 연동 파일 업로드 구성

2024. 12. 26. 18:27Java/Spring Boot

Map을 통해서 응답 처리해야 함

Case1

@PostMapping("/location/upload")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
    try {
        // Handle file storage
        Path path = Paths.get("uploads/" + file.getOriginalFilename());
        Files.write(path, file.getBytes());

        // Success response
        return ResponseEntity.ok(Map.of("success", true, "message", "File uploaded successfully!"));
    } catch (IOException e) {
        // Failure response
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("success", false, "message", "File upload failed."));
    }
}

Case2

@PostMapping("/location/upload")
public Map<String, Ojbect> uploadFile(@RequestParam("file") MultipartFile file) {
	Map<String, Object> result = new HashMap<String, Object>();
    
    try {
        // Handle file storage
        Path path = Paths.get("uploads/" + file.getOriginalFilename());
        Files.write(path, file.getBytes());

        // Success response
        result.push("success", true);
       result.push("message", "File uploaded successfully!");
     } catch (IOException e) {
        // Failure response
       result.put("success", false);
       result.put("message", "File upload failed.");
    }
    
    return result;
}

정상적인 응답

{
    "success": true,
    "message": "File uploaded successfully!"
}