vue web端實(shí)現(xiàn)圖片上傳

web端項(xiàng)目中有一個(gè)上傳圖片的功能,但是element-ui提供的上傳插件都不能滿足的我的需要,dropzone也因?yàn)槲覀兛蚣芊庋b的原因,在重置和初始化時(shí)都有一些問(wèn)題。在研究dropzone的問(wèn)題上花費(fèi)了很多時(shí)間,最后也沒(méi)解決,就索性自己寫了一個(gè)。

整理思路
功能方面:
1、上傳圖片,那肯定是input,type=“file”
2、獲取圖片,監(jiān)聽input的change事件
3、拿到圖片上傳
頁(yè)面樣式:
1、展示一個(gè)虛線框,沒(méi)有圖片時(shí)中間顯示一個(gè)+號(hào),點(diǎn)擊選擇圖片;
2、有圖片時(shí)展示圖片,鼠標(biāo)懸浮在圖片上方時(shí)顯示移除按鈕,否則不展示移除按鈕

代碼如下:

<template>
   <div class="dropzone">
       <input ref="uploadInput"
              type="file"
              name="file"
              value=""
              accept="image/gif,image/jpeg,image/jpg,image/png"
              @change="selectImg($event)">
       <div :class="operationShow?'operation-div':'operation-div hide'">
           <img :src="defaultImg">
           <span class="remove"
                 @click="remove">移除</span>
       </div>
       <div :class="operationShow?'txt hide':'txt'">
           +
       </div>
   </div>
</template>
<script>
export default {
   props: {
       url: {
           default: "",
           type: String
       },
       imgSrc: {
           default: "",
           type: String
       },
       autoUpload: {
           default: true,
           type: Boolean
       }
   },
   data()
   {
       return {
           operationShow: false,
           uploadFile: "",
           defaultImg: process.env.BASE_API + "/service-admin/" + this.imgSrc
       };
   },
   watch: {
       imgSrc(newsVal, oldVal)
       {
           this.init(newsVal);
       }
   },
   mounted()
   {
       this.init(this.imgSrc);
   },
   methods: {
       //選擇圖片
       selectImg(e)
       {
           const imgFile = e.target.files[0];
           if (imgFile)
           {
               this.uploadFile = imgFile;
               let reader = new FileReader();
               reader.readAsDataURL(imgFile);
               reader.onload = (event) =>
               {
                   this.defaultImg = reader.result;
                   this.operationShow = true;
                   if (this.autoUpload)
                   {
                       this.upload();
                   }
               };
           }
       },
       upload()
       {
           //將圖片轉(zhuǎn)成FormData類型數(shù)據(jù)
           let formData = new FormData();
           formData.append("file", this.uploadFile);
           ///通知父級(jí)上傳圖片
           this.$emit("uploadImg", formData);
       },
       remove()
       {
           // 圖片設(shè)為空
           this.defaultImg = "";
           // 隱藏圖片層,展示選擇圖片層
           this.operationShow = false;
           //通知父級(jí)移除圖片
           this.$emit("removeImg");
       },
       init(data)
       {
           //圖片不為空時(shí),顯示圖片層并展示圖片,input層隱藏
           if (data !== undefined && data !== "" && data !== null)
           {
               this.operationShow = true;
               this.defaultImg = process.env.BASE_API + "/" + data;
           }
           else
           {
               //圖片為空時(shí),不顯示圖片層,顯示input層
               this.defaultImg = "";
               this.operationShow = false;
           }
       }
   }
};
</script>
<style   rel="stylesheet/scss" lang="scss" >
@mixin base{
   position: absolute;
   top: 5%;
   height: 100%;
   width: 100%;
}
.dropzone{
   position: relative;
   height: 200px;
   max-width: 200px;
   width:100%;
   border: 1px dashed #ccc;
   box-sizing: border-box;
   input{
       @include base;
       opacity: 0;
       z-index: 10;
   }
   .operation-div{
       @include base;
       z-index: 100;
       text-align: center;
       img{
           width: 80%;
           height: 80%;
       }
       &:hover>.remove{
           display: block;
       }
       .remove{
           display: block;
           height: 10%;
           width: 100%;
           display: none;
           text-align: center;
           cursor: pointer;
       }
       .remove:hover{
           color: #409EFF;
       }
   }
   .txt{
       position: absolute;
       width: 100%;
       height: 30px;
       font-size: 40px;
       line-height: 30px;
       top: 50%;
       transform: translateY(-50%);
       text-align: center;
       color: #aaa;
       z-index: 1;
   }
   .hide{
       display: none;
   }

}
</style>

在父組件中使用:

<el-form-item
                    label="圖片"
                    prop="pic">
                    <form-upload-image
                        :auto-upload="true"
                        :img-src="form.data.pic" // form表單的數(shù)據(jù)
                        @uploadImg="uploadImg"
                        @removeImg="removeImg"/>
                </el-form-item>
// 上傳圖片
        uploadImg(formData)
        {
            //手動(dòng)校驗(yàn)圖片輸入框
            this.$refs["dataForm"].validateField("pic");
           //使用axios上傳圖片,repo是自己寫的axios攔截器
            new Repo({
                url: 'url',
                method: "post",
                data: formData,
                headers: { "Content-Type": "multipart/form-data" }
            }).then((response) =>
            {
               // 上傳成功,清空校驗(yàn)信息
                this.$refs["dataForm"].clearValidate("pic");
                //修改form data數(shù)據(jù)
                this.form.data.pic = response.data[0];
            });
        },
        // 移除圖片
        removeImg()
        {
           //修改form data數(shù)據(jù)
            this.form.data.pic = "";
            //手動(dòng)校驗(yàn)圖片輸入框
            this.$refs["data-form"].$refs["default"].validateField("pic");
        }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML標(biāo)準(zhǔn)。 注意:講述HT...
    kismetajun閱讀 28,804評(píng)論 1 45
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,245評(píng)論 4 61
  • 摘要: 之前用Selenium做UI自動(dòng)化測(cè)試從初學(xué)到熟練碰到過(guò)很多問(wèn)題,這里就不一一細(xì)說(shuō)了,所以把最基本的操作都...
    Vicky_習(xí)慣做唯一閱讀 11,643評(píng)論 1 23
  • 本女子年芳二八,普通的家庭,普通的工作,普通的生活。 越長(zhǎng)大,越能感覺(jué)是在逆風(fēng)而行。 從不怨天尤人,對(duì)于未能實(shí)現(xiàn)的...
    有多樂(lè)閱讀 436評(píng)論 0 1
  • 明明是悶熱的盛夏 卻仿佛置身在冰涼的夜 一群嬉笑的人 本應(yīng)一同走過(guò) 卻為何毀滅我 該放棄的時(shí)光與人 燃燒的熟悉空間...
    木子kivi閱讀 269評(píng)論 0 0

友情鏈接更多精彩內(nèi)容