본문 바로가기

Spring Boot

[Svelte + Springboot] Svelte에서 파일업로드 구현

반응형

Html

<input type="file" bind:value={file} />

 

javascript

import { createEventDispatcher } from "svelte";

const dispatch = createEventDispatcher();

async function uploadFile() {
  const formData = new FormData();
  formData.append("file", file);

  const response = await fetch("/api/upload", {
    method: "POST",
    body: formData
  });

  const data = await response.json();
  dispatch("upload-success", data);
}

 

Spring Boot 애플리케이션에서 파일을 수신할 REST을 생성합니다.

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")
public class FileUploadController {
  @PostMapping("/upload")
  public void uploadFile(@RequestParam("file") MultipartFile file) {
    // Save the file to disk or process it as needed
  }
}
반응형