文件上傳,需當上傳的文件類型為圖片的時候,需要限制圖片的寬高。
此處采用了new Promise異步加載的方式,等圖片上傳加載完成后,
頁面代碼:
1 <el-form-item label="廣告文件" style="width: 98%" v-if="dialogStatus!='view'"> 2 <el-upload 3 class="upload-demo" 4 drag 5 :action=actionURL 6 :data={bizType:10} 7 :limit=1 8 :multiple = false 9 :file-list="fileList" 10 :on-remove="removeFile" 11 :before-upload="beforeUpload" 12 :on-exceed="handleExceed" 13 :on-success = 'handleAvatarSuccess'> 14 <i class="el-icon-upload"></i> 15 <div class="el-upload__text"> 16 <div>將文件拖到此處,或<em>點擊上傳</em></div> 17 </div> 18 </el-upload> 19 <div class="tipCls" :class="{'fontWeightCls': form.adType==0}">圖片:jpg,png,gif,webp,JPEG</div> 20 <div class="tipCls" :class="{'fontWeightCls': form.adType==1}">視頻:3gp,mp4,mkv</div> 21 <div class="tipCls" :class="{'fontWeightCls': form.adType==2}">文本:txt</div> 22 <div class="tipCls" :class="{'fontWeightCls': form.adType==3}">聲音: mp3,mkv,wav,ogg, 3gp, mp4,m4a,aac, ts,flac</div> 23 </el-form-item>
上傳前檢查事件:
1 beforeUpload(file){ 2 const fileTypeName = (file.name).substring(file.name.lastIndexOf('.')*1 + 1*1); // 獲取后綴名 3 // (0圖片,1視頻,2文字,3聲音) 4 let supportFormat = ['mp3','mkv','wav','ogg','3gp','mp4','m4a','aac','ts','flac', '3gp','mp4','mkv','txt', 'jpg', 'png', 'gif', 'JPEG']; 5 if(this.form.adType === 0){ 6 supportFormat=['jpg', 'png', 'gif', 'JPEG']; 7 } else if(this.form.adType === 1){ 8 supportFormat=['3gp','mp4','mkv']; 9 } else if(this.form.adType === 2){ 10 supportFormat=['txt']; 11 } else if(this.form.adType === 3){ 12 supportFormat =['mp3','mkv','wav','ogg','3gp','mp4','m4a','aac','ts','flac']; 13 } 14 let index = supportFormat.indexOf(fileTypeName); 15 if(index == -1){ // 說明核實不符合 16 this.$message.warning('上傳文件的格式不合符,請重新上傳!'); 17 return false; 18 } else { 19 20 // 圖片文件大小限制,限制寬高分別為1280px和800px 21 if(this.form.adType == 0) { 22 let _this = this; 23 let imgWidth=""; 24 let imgHight=""; 25 const isSize = new Promise(function (resolve, reject) { 26 let width = 1280; 27 let height = 800; 28 let _URL = window.URL || window.webkitURL; 29 let img = new Image(); 30 img.onload = function () { 31 imgWidth = img.width; 32 imgHight = img.height; 33 let valid = img.width == width && img.height == height; 34 valid ? resolve() : reject(); 35 } 36 img.src = _URL.createObjectURL(file); 37 }).then(() => { 38 return file; 39 }, () => { 40 _this.$message.warning({message: '上傳文件的圖片大小不合符標准,寬需要為1280px,高需要為800px。當前上傳圖片的寬高分別為:'+imgWidth+'px和'+imgHight+'px', btn: false}) 41 return Promise.reject(); 42 }); 43 console.log(isSize); 44 return isSize; 45 }else { 46 return true; 47 } 48 } 49 },