TIL_2024_01_26

이종현·2024년 1월 26일
0

Today_I_Learned

목록 보기
128/145
post-thumbnail

Today 요약

  1. 리액트 강의

1. What I Learned?

리액트 강의

input 타입 file에서 허용가능한 타입 명시하기

file 타입 input에서 평소에 그냥 사용하곤 했었는데, 아래와 같이 accpet 속성으로 원하는 파일만 허용할 수 있다.

<input type="file" accept="image/*" name="image" />

이미지 타입 뿐만 아니라 다른 타입도 명시가 가능하다.

<input type="file" id="soundFile" accept="audio/*" />
<input type="file" id="videoFile" accept="video/*" />
<input type="file" id="imageFile" accept="image/*" />

*표시는 모든 확장자가 가능하다는 걸 표현한 것이다.

클라우디너리에 이미지 업로드하기

firebase은 firestore를 이용해서 이미지를 업로드해도 되지만, 강의를 듣다가 클라우디너리라는 것을 알게되었다. 아주 작은 단위의 프로젝트이면서 트래픽이 생각보다 많지 않은 경우라면 firebase나 클라우디너리를 이용해서 이미지나 비디오를 업로드해서 사용하면 좋을 것 같다.

이미지를 업로드하는 대략적인 코드는 아래와 같다.

클라우디너리에서 요구하는 URL 형식이 있고, upload_preset을 formdata에 저장한다음 post 요청으로 data를 보내면 응닶값으로 클라우디너리에 저장된 이미지의 url을 리턴받을 수 있다.

const uploadImage = (file: File) => {
  const CLOUDINARY_URL = 'https://api.cloudinary.com/v1_1/demo/image/upload'

  const data = new FormData()

  data.append('file', file)
  data.append('upload_preset', 'my_preset')

  return fetch(CLOUDINARY_URL, {
    method: 'POST',
    body: data
  })
    .then((res) => res.json())
    .then((data) => data.url)
}

export default uploadImage
const imageURL = await uploadImage(file as File)
await addNewProduct(product, imageURL)

그렇게 해서 addNewProduct라는 함수에 전달해서 firebase의 실시간 데이터베이스에 저장해서 사용했다.

profile
데이터리터러시를 중요하게 생각하는 프론트엔드 개발자

0개의 댓글