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
'VUE' 카테고리의 다른 글
Vue.js Basic Syntax Guide: Numeric and String Conversion with Rounding Examples (0) | 2024.03.15 |
---|---|
vue 자식컴포넌트 object 타입 선언 및 초기화 (0) | 2023.09.20 |
localStorage sessionStorage set get remove (0) | 2023.05.21 |
vue.js 에서 router 호출 전 store 에 저장하기 (0) | 2023.05.11 |
vue.js 에서 파일 업로드 이미지파일 미리보기 구현 예제 (0) | 2023.05.09 |