본문 바로가기

Spring Boot

[React + Spring Boot ] Spring Boot 백엔드를 사용하여 React 앱에서 파일 업로드를 구현하는 방법

반응형

React component

import React, { useState } from 'react';

const FileUploader = () => {
  const [file, setFile] = useState(null);

  const handleFileUpload = async e => {
    setFile(e.target.files[0]);
  };

  const handleSubmit = async e => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await fetch('http://localhost:8080/upload', {
        method: 'POST',
        body: formData
      });
      console.log(await response.text());
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" onChange={handleFileUpload} />
      <button type="submit">Upload</button>
    </form>
  );
};

export default FileUploader;

 

Spring Boot controller

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.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class FileUploadController {
  @PostMapping("/upload")
  public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
    byte[] bytes = file.getBytes();
    Path path = Paths.get("src/main/resources/static/" + file.getOriginalFilename());
    Files.write(path, bytes);
    return "File uploaded successfully";
  }
}

사용자가 파일을 선택하여 서버에 업로드할 수 있는 양식으로 응답 구성 요소를 설정합니다. 폼 데이터는 파일 업로드를 처리하는 스프링 부트 엔드포인트로 다중 부품/폼 데이터 요청으로 전송됩니다. 이 예에서는 업로드된 파일이 스프링 부트 프로젝트의 디렉터리에 저장됩니다. 

반응형