본문 바로가기
개발지식

Java와 JavaScript를 활용한 multipart기능 파일 업로드 방법

by hunovator 2024. 2. 12.
반응형

파일 업로드는 웹 개발에서 흔한 작업 중 하나이며, Java와 JavaScript를 사용하여 multipart/form-data로 파일을 업로드하는 방법에 대해 알려드리겠습니다. 이를 위해 서버 측에서는 Java의 Spring Framework를 사용하고, 클라이언트 측에서는 JavaScript와 HTML을 사용할 것입니다.


1. 서버 측 (Java - Spring Framework)

1.1. 의존성 추가

<!-- pom.xml 파일에 추가 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

1.2. 파일 업로드 처리 컨트롤러 생성

import org.springframework.http.ResponseEntity;
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.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/files")
public class FileUploadController {

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        // 파일 업로드 처리 로직
        // 여기에서 파일 저장, 데이터베이스에 저장 등의 작업을 수행할 수 있습니다.

        return ResponseEntity.ok("File uploaded successfully!");
    }
}

서버 측: Spring Framework를 사용하여 파일 업로드를 처리하는 컨트롤러를 생성했습니다. @RequestParam("file") 어노테이션을 통해 클라이언트에서 전송한 파일을 받아 처리합니다.

2. 클라이언트 측 (JavaScript)

2.1. HTML Form 생성

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <form id="uploadForm">
        <label for="file">Choose a file:</label>
        <input type="file" id="file" name="file" required>
        <br>
        <input type="submit" value="Upload">
    </form>

    <script src="upload.js"></script>
</body>
</html>


2.2. JavaScript 파일 업로드 처리

document.getElementById('uploadForm').addEventListener('submit', function (event) {
    event.preventDefault();

    const formData = new FormData();
    const fileInput = document.getElementById('file');

    formData.append('file', fileInput.files[0]);

    fetch('http://localhost:8080/api/files/upload', {
        method: 'POST',
        body: formData,
    })
    .then(response => response.json())
    .then(data => {
        console.log('Success:', data);
    })
    .catch(error => {
        console.error('Error:', error);
    });
});


클라이언트 측: HTML Form을 생성하고, JavaScript를 사용하여 파일을 선택하고 업로드하는 동작을 처리합니다. FormData 객체를 사용하여 파일을 서버에 전송합니다.

 

이 예제에서는 간단한 형태의 파일 업로드를 다루었습니다. 더 복잡한 상황에서는 보안, 오류 처리, 파일 저장 경로 등을 추가로 고려해야 할 수 있습니다. 또한, 서버와 클라이언트 간의 CORS (Cross-Origin Resource Sharing) 설정도 필요할 수 있습니다.

반응형