본문 바로가기
자바스크립트

[Javascript] 이미지 파일 업로드 구현

by devebucks 2022. 5. 13.
728x90

결과

참고

개발자를 위한 웹 기술 > Web API > File > 웹 어플리케이션에서 파일 사용하기

개발자를 위한 기술 > Web API > Blob

기능 요구사항

프로필 사진 업로드 기능

이미지 파일을 업로드 후, 업로드한 이미지 미리보기

 

구현 방법 결정하기

방법1. javascript의 FileReader 객체

FileReader.readAsDataURL()

- 엄청 긴, 스트링을 URL로 반환하기 때문에, 속도가 느리다.

 

방법2. URL.createObjectURL(object)

주어진 객체를 가리키는 URL을 DOMString으로 반환한다. service worker에서 사용 안 됨.

파라미터 object는 File, Blob, MediaSource 객체를 넣을 수 있음

input file upload -> Blob 객체로 변경 -> URL.createObjectURL(Blob) 으로 브라우저 컨텍스트에서만 사용할 수 있는 URL로 변환

- blob객체의 url 주소값으로 이미지를 불러 올 수 있다. 메모리에 올라가 있는 주소여서, 객체를 새로 만들 필요가 없다. 속도가 빠르다.

 

구현 방법

input file upload  -> URL.createObjectURL(file[0]) 으로 브라우저 컨텍스트에서만 사용할 수 있는 URL로 변환

HTML

<!-- 프로필 사진 -->
<div class="mt-16 tablet:mt-[100px] tablet:ml-[72px] tablet:min-w-[168px] mx-auto mb-6 relative">
    <!-- 👇 여기에 이미지가 갱신됨. -->
    <img ref="profileImg" src="~/static/fonts/gguge-icon/defaultProfile2.svg" class="h-20 tablet:h-[168px] object-cover rounded-full" />
        <label for="attachment" class="absolute top-[50px] tablet:top-[100px] right-0 cursor-pointer">
          <div class="relative">
            <div class="rounded-full bg-[#333333] w-8 h-8 tablet:w-16 tablet:h-16 opacity-50 flex justify-center items-center"></div>
            <img
              src="~/static/fonts/gguge-icon/Interface/camera.svg"
              class="w-[18.29px] h-[18.29px] tablet:w-[36.57px] tablet:h-[34.52px] absolute top-1/2 left-1/2 ab-center"
            />
          </div>
        </label>
        <input
          id="attachment"
          type="file"
          class="hidden file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold"
          accept="image/*"
          @change.prevent="selectFile"
        />
</div>

JAVASCRIPT

selectFile({ target }) {
  // 파일 용량 확인
  if (!validateFileSize(target, 30)) {
    return;
  }
  this.formFile = target.files;  // 파일 객체
  this.fileTitle = this.formFile[0].name;  // 파일 이름
  this.$refs.profileImg.src = URL.createObjectURL(this.formFile[0]); // 파일 URL 변환
},

 

에러 발생

Error
500
Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.

원인: input에서 업로드한 target.files 객체를 그대로 넣어서 발생함. Blob 객체를 넣어야 함.

 

input에서 업로드한 파일 객체를 Blob으로 변형하기

 

 

Blob(Binary Large Object): Javascript에서 이미지, 사운드, 비디오 같은 멀티 데이터를 다룰 때 사용함. 그냥 file 객체가 아닌, Blob을 사용하는 이유는, 

 

new FIle()이 Blob에 기반한 인터페이스이다. new File()은 사용자 시스템의 파일을 지원하기 위해 Blob 인터페이스를 상속해 기능을 확장한 것임.

 

 

Blob이 아닌, 객체와 데이터를 Blob으로 변경하려면, Blob() 생성자를 사용하면 된다.

728x90

댓글