221108 TIL | 트위터 클론코딩_(3)

오늘 한 일

  • 노마드코더 트위터 클론코딩 실습
    • FileReader API 이용하여 썸네일 등록
    • Storage 생성
    • 파일 업로드, 읽어오기, 삭제

파일 업로드

  • FileReader API 이용하여 썸네일 등록
  • Storage 생성
const onFileChange = (event) => {
    const {
      target: { files },
    } = event;
    const theFiles = files[0];
    const reader = new FileReader();
    reader.onloadend = (finishedEvent) => {
      const {
        currentTarget: { result },
      } = finishedEvent;
      setAttachment(result);
    };
    reader.readAsDataURL(theFiles);
  };

사진 id 설정을 위해 랜덤 식별자를 생성하는 uuid 라이브러리를 설치

  • npm install uuid
import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

파일 업로드

// return Reference
const fileRef = storageService.ref().child(`${userObj.uid}/${uuidv4()}`); 

// 폴더에 이미지 넣음
// 완료 후 return UploadTaskSnapshot
const response = await fileRef.putString(attachment, "data_url");
  • 유저 아이디로 된 폴더가 생성되고

001

  • 폴더 안에 이미지 파일이 들어가도록 설정할 수 있다.
    • 타입을 지정하지 않아도 image 타입이 들어간다.

002

// 이미지가 저장된 stroage 주소를 받음.
attachmentUrl = await response.ref.getDownloadURL();

사진 업로드

003

사진 삭제

  • delete()는 Referance의 메서드이고, refFromURL() 메서드를 이용하면 Reference를 얻을 수 있다.
await storageService.refFromURL(hweetObj.attachmentUrl).delete;

firebase의 Referance로 많은 것을 할 수 있다..