그냥 개발자 블로그

[SvelteKit] 이미지 파일 multipart/form-data로 보내고 업로드하기 본문

프로그래밍팁/svelte

[SvelteKit] 이미지 파일 multipart/form-data로 보내고 업로드하기

마음이파파 2023. 8. 9. 15:24

- SvelteKit에서 이미지 파일을 업로드 하고자 할때

- multipart/form-data로 파일 전송하고자 할때

- 이미지파일 버퍼로 변환 시키고자 할때

 

+page.svelte (보내는 곳)

const handleFileChange = async (e) => {

    const imgFormData = new FormData();
    imgFormData.append("image",files[0]);

    const response = await fetch("/api/banner/file",{
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        headers: {
            enctype: 'multipart/form-data', // 파일 형식 확인
        },
        body:imgFormData
    });

}

 

 

+server.js (받고 업로드하는 곳)

import { json } from "@sveltejs/kit";
import { writeFile } from 'fs/promises'; // Node.js의 promise 버전 파일 시스템 모듈
import path from "path";

export async function POST({request,cookies}){

    const now = new Date();
    const timestamp = now.getTime();
    
    const data = await request.formData();
    const file = data.get('image');


    // 파일을 저장할 경로를 지정합니다.
    const uploadPath = path.join(process.cwd(), 'static', 'images', timestamp+'.'+file.name.split('.').pop());

    // 파일을 서버 폴더에 저장합니다.
    const imageBufferData = Buffer.from(await file.arrayBuffer());
    await writeFile(uploadPath, imageBufferData);

    return json({msg:'ok',file:'/static/images/'+file.name},{status:200})
}