728x90

싱글 파일 업로드 일 경우 

<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 을 삭제하는 역할을 한다.

728x90

+ Recent posts