728x90

firebase 와 연동중이라면 vue3 에서 파일을 업로드 하고 다운로드 링크를 추출 하는 예제 이다. 이렇게 구현하면 백엔드 없이도 파일 업로드 구현이 가능하다. 

<template>
  <div>
    <input type="file" ref="fileInput" @change="uploadFile" />
    <progress v-if="uploading" :value="uploadProgress"></progress>
    <div v-if="downloadURL">
      <p>파일이 성공적으로 업로드되었습니다.</p>
      <a :href="downloadURL" download>다운로드 링크</a>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { getStorage, ref as storageRef, uploadBytes, getDownloadURL } from 'firebase/storage'

const fileInput = ref(null)
const uploading = ref(false)
const uploadProgress = ref(0)
const downloadURL = ref(null)
const fileRef = ref(null)

const storage = getStorage() // Firebase Storage 초기화

const uploadFile = async () => {
  if (!fileInput.value.files.length) {
    return
  }

  const file = fileInput.value.files[0]
  const storageReference = storageRef(storage, 'uploads/' + file.name)

  try {
    uploading.value = true

    // 파일 업로드
    const snapshot = await uploadBytes(storageReference, file, (snapshot) => {
      uploadProgress.value = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
    })
    
    //파일 다운로드 전체 링크 저장
     fileRef.value = snapshot.ref.fullPath;

    // 파일 다운로드 URL 가져오기
    downloadURL.value = await getDownloadURL(snapshot.ref)
  } catch (error) {
    console.error('파일 업로드 중 오류 발생:', error)
  } finally {
    uploading.value = false
  }
}
</script>
728x90

+ Recent posts