選擇照片上傳前如何實作預覽的功能,下面拆解成3個部分說明:
1. 上傳檔案
首先需要一個上傳檔案的HTML<input type="file" accept="image/*" @change="previewImage">根據上面的程式碼,我們需要一個 previewImage 的function來處理選擇的圖片檔。
2. 實作previewImage
接下來是js的程式部分,我們定義了兩個變數 preview 、 image,前者是存放預覽圖片,後者則是實際檔案。new Vue({
  data: function() {
    return {
      preview: null,
      image: null
    };
  },
  methods: {
    previewImage: function(event) {
      var input = event.target;
      if (input.files) {
        var reader = new FileReader();
        reader.onload = (e) => {
          this.preview = e.target.result;
        }
        this.image=input.files[0];
        reader.readAsDataURL(input.files[0]);
      }
    }
  }
});3. 顯示預覽
將 previewImage 儲存的結果顯示出來<template v-if="preview">
  <img :src="preview" />
  <p>file name: {{ image.name }}</p>
  <p>size: {{ image.size/1024 }}KB</p>
</template>
執行上面的程式碼就可以達到預覽的效果,最後只要透過API將 image 這個物件透過API丟到後台,就能完成檔案的上傳。(用formData檔案上傳)
更進階的部分,只要在 input tag中加上multiple 就能一次選擇多個檔案。
<input type="file" accept="image/*" multiple>除了預覽單一檔案,也能支援選擇多個檔案並預覽,有需要的話完整的原始碼已經放到codepen上,歡迎參考。
 
沒有留言:
張貼留言