싱글 파일 업로드 일 경우
<template>
<div>
<v-file v-model="file" accept="image/*" @change="onFileChange" />
<img v-if="previewImage" :src="previewImage" />
<button @click="uploadFile" :disabled="!file">Upload</button>
</div>
</template>
<script>
export default {
data() {
return {
file: null,
previewImage: null,
}
},
methods: {
onFileChange() {
if (this.file) {
this.previewImage = URL.createObjectURL(this.file)
} else {
this.previewImage = null
}
},
uploadFile() {
const formData = new FormData()
formData.append('file', this.file)
// Make your API call to upload the file with the formData
// ...
}
},
beforeDestroy() {
if (this.previewImage) {
URL.revokeObjectURL(this.previewImage)
}
}
}
</script>
다중파일 업로드 일 경우
<template>
<div>
<v-file v-model="files" accept="image/*" multiple @change="onFileChange" />
<div v-for="(preview, index) in previewImages" :key="index">
<img :src="preview" />
</div>
<button @click="uploadFiles" :disabled="!files || !files.length">Upload</button>
</div>
</template>
<script>
export default {
data() {
return {
files: [],
previewImages: [],
}
},
methods: {
onFileChange() {
this.previewImages = []
for (let i = 0; i < this.files.length; i++) {
const file = this.files[i]
if (file && file.type.startsWith('image/')) {
this.previewImages.push(URL.createObjectURL(file))
}
}
},
uploadFiles() {
const formData = new FormData()
for (let i = 0; i < this.files.length; i++) {
formData.append('files[]', this.files[i])
}
// Make your API call to upload the files with the formData
// ...
}
},
beforeDestroy() {
for (let i = 0; i < this.previewImages.length; i++) {
URL.revokeObjectURL(this.previewImages[i])
}
}
}
</script>
beforeDestroy
beforeDestroy 는 라이프사이클 훅 중 하나로
컴포넌트가 소멸 되기 직전에 호출된다.
따라서 위 예제에서는 이미지 파일의 URL 을 삭제하는 역할을 한다.
'VUE' 카테고리의 다른 글
localStorage sessionStorage set get remove (0) | 2023.05.21 |
---|---|
vue.js 에서 router 호출 전 store 에 저장하기 (0) | 2023.05.11 |
git checkout 브랜치 이동 안될때 (0) | 2023.05.02 |
vue.js data list 에 값을 나누고 천단위로 콤마도 추가 (0) | 2023.03.22 |
vue2 에서 vuex store 오류 (0) | 2023.01.22 |