1. 程式人生 > 實用技巧 >input type=file實現圖片上傳,預覽以及圖片刪除

input type=file實現圖片上傳,預覽以及圖片刪除

// html

<div class="preview" v-show="previewImg" @click="previewImg=''"><img :src="previewImg" alt="" /></div>
<div class="uploadBox2">
   <div class="uploadBtn uploadImg" v-for="(item,index) in imgDatas">
       <span class="close" @click="deleteImg(index)"></span
> <img :src="item" alt="" @click="previewImg=item"> </div>   <div class="uploadBtn">   <span class="iconadd">+</span>   <input type="file" accept="image/*" multiple @change="changeImage($event)"/>   </div> </div>
// css

.uploadBox2{
  display
: flex; display: -webkit-flex; flex-wrap: wrap; -webkit-flex-wrap: wrap; } .uploadBtn{ width: 60px; height: 60px; border: 1px dashed #E6E6E6; position: relative; margin: 0 8px 15px 0; } .uploadImg{ border: none; } .uploadBtn img{ width: 100%; height: 100%; } .uploadBtn input{ width: 100%
; height: 100%; opacity: 0; } .close{ width: 15px; height: 15px; line-height: 15px; text-align: center; position: absolute; top: -6px; right: -6px; color: #fff; background: rgba(0,0,0,0.6); border-radius: 50%; font-size: 10px; } .iconadd{ font-size: 20px; color: #E6E6E6; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); z-index: 0; } .preview{ position: fixed; top: 0; left: 0; bottom: 0; right: 0; z-index: 99; background: rgba(0,0,0,0.9); } .preview img{ width: 100%; height: 100%; object-fit: contain; vertical-align: middle; }
// JS

data(){
  return(){
      filesArr: [],
      imgDatas: [],
      previewImg: '', // 放大預覽圖片
  }  
},
methods: {
     // 上傳圖片
    changeImage(e){
      let files = e.target.files;
       // 如果沒有選中檔案,直接返回
      if (files.length === 0) {
        return;
      }
      let reader;
      let file;
      let imgDatas = this.imgDatas;
      for (let i = 0; i < files.length; i++) {
        file = files[i];
        this.filesArr.push(file);
        reader = new FileReader();
        if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
          reader.onload = function(e) {
            if (imgDatas.indexOf(this.result) === -1) { // 判斷數組裡值相同的無法上傳,具體看自己需求
              imgDatas.push(this.result);
            }
          };
          reader.readAsDataURL(file);
        }
      }
      e.target.value = ''// 清空value值防止 同一張圖片無法重複提交
    },
    // 刪除圖片
    deleteImg(index){
      this.filesArr.splice(index,1);
      this.imgDatas.splice(index,1);
      console.log(this.filesArr);
      console.log(this.imgDatas);
    },    
}

最後實現的效果:

(預覽放大圖片:)