클라이언트-서버 간 파일 업로드: Ajax로 파일업로드 하기

웹 개발에서 파일 업로드는 사용자에게 더 많은 기능과 편의성을 제공하는 중요한 부분입니다. 이번 블로그에서는 클라이언트 측에서 JavaScript를 사용하여 파일을 업로드하고, 서버 측에서는 Spring 프레임워크를 통해 업로드된 파일을 처리하는 방법에 대해 자세히 알아보겠습니다.





1. 클라이언트 측: JavaScript 파일 (script.js)

웹 페이지에는 파일 업로드를 처리하는 JavaScript 코드가 필요합니다. 아래는 간단한 파일 업로드 함수를 포함한 script.js 파일의 예제입니다.

function uploadFile() {
    var fileInput = document.getElementById('fileInput');
    
    // FormData 객체 생성
    var formData = new FormData();
    
    // 파일 추가
    formData.append('file', fileInput.files[0]);
    
    // Ajax 요청
    $.ajax({
        type: 'POST',
        url: 'upload', // Spring 컨트롤러 주소
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            console.log('파일 업로드 성공:', response);
        },
        error: function(error) {
            console.error('파일 업로드 실패:', error);
        }
    });
}


2. 서버 측: Spring 컨트롤러 (UploadController.java)

서버에서는 Spring 컨트롤러를 사용하여 업로드된 파일을 수신하고 처리합니다. 아래는 UploadController.java 파일의 예제입니다.


import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class UploadController {

    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        // 파일 저장 경로
        String uploadPath = "uploads/";

        // 업로드된 파일 처리
        if (!file.isEmpty()) {
            try {
                // 업로드 디렉토리가 없으면 생성
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdir();
                }

                // 저장될 파일 경로
                String filePath = uploadPath + file.getOriginalFilename();
                File dest = new File(filePath);

                // 파일 저장
                file.transferTo(dest);

                return new ResponseEntity<>("파일 업로드 성공", HttpStatus.OK);
            } catch (IOException e) {
                return new ResponseEntity<>("파일 업로드 실패: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } else {
            return new ResponseEntity<>("업로드된 파일이 없습니다.", HttpStatus.BAD_REQUEST);
        }
    }

    @RequestMapping("/")
    public String index() {
        return "index";
    }
}



3. 마무리 및 주의사항

이제 클라이언트와 서버 간의 파일 업로드가 완성되었습니다. 하지만 실제 서비스에서는 보안 및 예외 처리를 강화하고 파일 업로드를 안전하게 다루기 위해 더 많은 고려가 필요합니다. 또한, 프로젝트에 따라 파일 저장 경로 및 서버 스크립트 주소를 적절히 수정하여 사용해야 합니다.




Leave a Comment