31) FileReader ?

이희주·2022년 6월 21일
0
post-thumbnail

React

오늘 수업 내용

이미지 미리보기

이미지를 보기 위해서는 이미지 경로(주소)가 필요한데, 이미지 서버에 이미지를 등록하고 등록한 이미지 주소를 불러와야 다른곳에서도 이미지를 불러올 수 있었다

하지만 이미지를 올려놓고 다시 뒤로가기를 하면 이미지 서버에는 이미지가 올라가지만, 사용되는 곳은 없기 때문에 데이터 낭비와 서버 과부하가 오게 된다

그래서 이미지 주소를 서버에서 가져오는게 아니라, 미리보기 용으로 만들어주는 방법을 사용 !

const onChangeFile = (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) {
      alert("파일을 첨부해주세요");
      return;
    }

    // FileReader : 파일과 관련된 다양한 기능을 가지고 있음 ! 그중에 파일을 읽어서 url 주소로 만들어줄거야
    const fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    // 파일로 url을 만들어주기
    fileReader.onload = (data) => {
      // 파일이 다 만들어지면 결과가 data에 들어옴(data.target.result 라는 이름으로)
      if (typeof data.target?.result === "string") {
        console.log(data.target?.result);
        setImageUrl(data.target?.result);
      }
    };
  };

임시 url로 api 요청하기

  const onClickGraphqlApi = async () => {
    // 1. upload file api 요청
    const resultFile = await uploadFile({ variables: { file } });

    // 2. upload file api 받아오고 url만 꺼내기
    const url = resultFile.data.uploadFile.url;

    // 3. createBoard 요청
    const result = await createBoard({
      variables: {
        createBoardInput: {
          writer: "이망고",
          password: "1234",
          title: "제목",
          contents: "내용",
          images: [url],
          //images는 배열로 들어간다!!
        },
      },
    });
    console.log(result);
  };

Promise & Promise.all()

// Promise
	const onClickPromise = async () => {
    	const result1 = await new Promise((resolve, reject) => {
      		setTimeout(() => {
        		resolve("https://dog1.jpg");
      		}, 1000);
    	}).then((res) => console.log(res));
      
        const result2 = await new Promise((resolve, reject) => {
              setTimeout(() => {
                  resolve("https://dog2.jpg");
              }, 3000);
          }).then((res) => console.log(res));
     };


// Promise.all()
	const onClickPromiseAll = async () => {
		const result = await Promise.all([
			setTimeout(() => {resolve("https://dog1.jpg")}, 1000)}).then((res) => console.log(res));
      		setTimeout(() => {resolve("https://dog2.jpg")}, 3000)}).then((res) => console.log(res))
		])
	};

Promise

result1, result2 순서대로 실행됨 (4초정도)

Promise.all()

all 안에 들어있는 함수들을 동시에 실행해서 약 3초의 시간이 소요됨

fileReader를 사용해서 이미지를 등록할 때, Promise.all을 이용해서 이미지를 한번에 여러장 등록 할 수 있다

  • promise.all() - map 참고
	const onClickPromiseAll = async () => {
		const result = await Promise.all(["http://storage.url1.jpg",
		"http://storage.url1.jpg", "http://storage.url1.jpg"].map((el)
			=> new Promise((resolve, reject) => {
					setTimeout(() => {
						resolve(el)
					}, 3000)
			})
		))
	};

LazyLoad vs PreLoad

LazyLoad

페이지를 읽어들이는 시점에 중요하지 않은 리소스 로딩을 추후에 하는 기술
스크롤을 내리면서 이미지가 보여져야 할 때마다 이미지를 로드

PreLoad

페이지를 읽어들일 때 미리 리소스를 받아놓는 기술
모든 데이터들을 미리 로드해놓고 대기하는 방식

npm에서 LazyLoad 라이브러리를 검색해서 사용할 수 있음

이미지 확장자 Webp

구글에서 만든 이미지 포맷(웹피)

gif, png, jpeg와 같은 이미지 확장자로 이미지를 압축했을 때 기존 PNG, JPEG보다 약 30% 정도 용량을 줄일 수 있는 장점이 있음

webp 확장자 변환 사이트

  1. selec File 2. webp 선택 3. convert 누르면 완료

++

이미지 라이브러리 참고

npm 참고

React-lazy-load
React-dropzone
ant-design
React-beautiful-dnd

  1. 포트폴리오에 들어가는 gif 들 webp로 변경해서 용량 줄여주기
profile
어제보다 오늘 발전하는 프론트엔드 개발자

0개의 댓글