반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

이미지 업로드 하기 본문

인프런, 유데미/Slack 클론 코딩

이미지 업로드 하기

5_hyun 2022. 7. 31. 22:23

이미지 업로드

<Container onDrop={onDrop} onDragOver={onDragOver}>

onDragOver 하는 동안 사진을 끌고 다닌다. onDrop는 사진을 놓는다. 따라서 onDragOver는 계속 호출이된다.

 

      {dragOver && <DragOver>업로드!</DragOver>}

-onDragOver

  const onDragOver = useCallback((e: any) => {
    e.preventDefault();
    console.log(e);
    setDragOver(true);
  }, []);

이렇게 해서 '업로드!'를 화면에 띄워준다.

 

-OnDrop

 const onDrop = useCallback(
    (e: any) => {
      e.preventDefault();
      console.log(e);
      const formData = new FormData();
      //dataTransfer 안에 이미지의 정보가 있다. 브라우저마다 items 혹은 files에 들어있다.
      if (e.dataTransfer.items) {
        // Use DataTransferItemList interface to access the file(s)
        for (let i = 0; i < e.dataTransfer.items.length; i++) {
          // If dropped items aren't files, reject them
          if (e.dataTransfer.items[i].kind === 'file') {
            const file = e.dataTransfer.items[i].getAsFile();
            console.log('... file[' + i + '].name = ' + file.name);
            formData.append('image', file);
          }
        }
      } else {
        // Use DataTransfer interface to access the file(s)
        for (let i = 0; i < e.dataTransfer.files.length; i++) {
          console.log('... file[' + i + '].name = ' + e.dataTransfer.files[i].name);
          formData.append('image', e.dataTransfer.files[i]);
        }
      }
      axios.post(`/api/workspaces/${workspace}/dms/${id}/images`, formData).then(() => {
        setDragOver(false);
        localStorage.setItem(`${workspace}-${id}`, new Date().getTime().toString());
        mutateChat();
      });
    },
    [workspace, id, mutateChat],
  );

OnDrop는 https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop

 

File drag and drop - Web APIs | MDN

HTML Drag and Drop interfaces enable web applications to drag and drop files on a web page. This document describes how an application can accept one or more files that are dragged from the underlying platform's file manager and dropped on a web page.

developer.mozilla.org

이 사이트에서 가져온 것이다.

브라우저 마다 이미지의 정보가 items 아니면 files에 들어있다. 보통 서버로 파일을 보낼 때는 formData를 사용한다. formdata에 대한 내용은 https://www.zerocho.com/category/HTML&DOM/post/59465380f2c7fb0018a1a263

 

https://www.zerocho.com/category/HTML&DOM/post/59465380f2c7fb0018a1a263

 

www.zerocho.com

제로초님의 블로그를 참고하면 될 것 같다.

 

https://github.com/ZeroCho/sleact/blob/master/front/components/Chat/index.tsx

 

GitHub - ZeroCho/sleact

Contribute to ZeroCho/sleact development by creating an account on GitHub.

github.com

마지막으로 이 코드도 다시 체크해야 한다.

728x90
반응형
Comments