오늘 수업 내용
이미지를 보기 위해서는 이미지 경로(주소)가 필요한데, 이미지 서버에 이미지를 등록하고 등록한 이미지 주소를 불러와야 다른곳에서도 이미지를 불러올 수 있었다
하지만 이미지를 올려놓고 다시 뒤로가기를 하면 이미지 서버에는 이미지가 올라가지만, 사용되는 곳은 없기 때문에 데이터 낭비와 서버 과부하가 오게 된다
그래서 이미지 주소를 서버에서 가져오는게 아니라, 미리보기 용으로 만들어주는 방법을 사용 !
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);
}
};
};
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
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))
])
};
result1, result2 순서대로 실행됨 (4초정도)
all 안에 들어있는 함수들을 동시에 실행해서 약 3초의 시간이 소요됨
fileReader를 사용해서 이미지를 등록할 때, Promise.all을 이용해서 이미지를 한번에 여러장 등록 할 수 있다
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
페이지를 읽어들이는 시점에 중요하지 않은 리소스 로딩을 추후에 하는 기술
스크롤을 내리면서 이미지가 보여져야 할 때마다 이미지를 로드
PreLoad
페이지를 읽어들일 때 미리 리소스를 받아놓는 기술
모든 데이터들을 미리 로드해놓고 대기하는 방식
npm에서 LazyLoad 라이브러리를 검색해서 사용할 수 있음
구글에서 만든 이미지 포맷(웹피)
gif, png, jpeg와 같은 이미지 확장자로 이미지를 압축했을 때 기존 PNG, JPEG보다 약 30% 정도 용량을 줄일 수 있는 장점이 있음
- selec File 2. webp 선택 3. convert 누르면 완료
++
npm 참고
React-lazy-load
React-dropzone
ant-design
React-beautiful-dnd