클립보드 image upload

Acorn Academy 구라쌤·2024년 11월 20일

버퍼에 복사된 이미지 데이터를 서버에 업로드하는 방법

버퍼에 저장된 이미지 데이터를 서버에 업로드하려면, 클라이언트 측에서 이미지 데이터를 추출하고 이를 서버로 전송해야 합니다. 아래는 이 과정을 설명합니다.


1. 클라이언트 측 작업

(1) 이미지 데이터를 읽는 방법

웹 브라우저나 애플리케이션에서 이미지 데이터를 클립보드(버퍼)에서 읽어올 수 있습니다.

예: JavaScript로 클립보드에서 이미지 읽기

  1. 클립보드 이벤트를 감지하여 데이터를 가져옵니다.
  2. 이미지를 Blob 객체로 변환합니다.
document.addEventListener("paste", (event) => {
    const clipboardItems = event.clipboardData.items;
    for (const item of clipboardItems) {
        if (item.type.startsWith("image/")) {
            const blob = item.getAsFile();

            // 이미지를 서버로 업로드
            uploadToServer(blob);
        }
    }
});

function uploadToServer(blob) {
    const formData = new FormData();
    formData.append("file", blob, "pasted_image.png");

    fetch("https://yourserver.com/upload", {
        method: "POST",
        body: formData,
    })
    .then((response) => response.json())
    .then((data) => console.log("Upload success:", data))
    .catch((error) => console.error("Upload failed:", error));
}

0개의 댓글