參考地址: element ui的照片牆 默認顯示照片
照片顯示的數據格式是:[{name: '', url: ''}],:file-list=""默認顯示的圖片
實際項目開發中需要處理兩個問題:① 從后端返回的二進制數據處理為前端image可識別的base64格式; ② 如果從后端返回的數據不為空,那么顯示圖片,並且隱藏上傳按鈕,只有當刪除展示的圖片后才可繼續上傳
問題①:處理方式可參照:前端imageBuffer設置圖片src(后端返回二進制流圖片)
問題②:處理方式如下:
// 頁面架構 <tr> <td>項目截圖:</td> <td> <el-upload action="" :class="{hide: hideUpload}" :http-request="uploadScreenShot" list-type="picture-card" :before-upload="isPic" :on-preview="handlePictureCardPreview" :on-remove="screenShotRemove" :on-change="screenShotChange" :limit="1" :file-list="dialogImageUrlArray"> <i class="el-icon-plus"></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt=""> </el-dialog> </td> </tr>
data() { return { projectScreenShot: [], // 項目截圖 - 用於存儲url dialogImageUrl: '', // 項目截圖 - 圖片的url dialogImageUrlArray: [{ url: '' }], // 項目截圖 - 圖片的url hideUpload: false, // 項目截圖:是否隱藏上傳按鈕 dialogVisible: false, } }
如果限制只能上傳1張圖片,且圖片上傳成功后隱藏上傳按鈕,需要設置以下幾個屬性: :on-preview = ''、:on-remove = ''、:on-change=''
// 項目截圖:點擊'放大'按鈕,可以放大圖片(點擊文件列表中已上傳的文件時的鈎子) handlePictureCardPreview(file) { this.dialogImageUrl = file.url; this.dialogVisible = true; }, // 項目截圖:刪除上傳文件on-remove事件(文件列表移除文件時的鈎子) screenShotRemove(file, fileList) { this.hideUpload = fileList >= 1; // 上傳的項目截圖 < 1時,顯示上傳按鈕 }, // 項目截圖:上傳文件on-change事件(文件上傳時的鈎子) screenShotChange(file, fileList) { this.hideUpload = fileList.length >= 1; // 上傳的項目截圖 >= 1時,隱藏上傳按鈕 },
處理從后端返回的二進制數據,並把處理好的路徑賦值給 this.dialogImageUrlArray[0].url ,隱藏上傳按鈕
// 獲取'項目截圖'的url this.$http({ url: this.$http.adornUrl('/web/showimgFile'), method: 'get', responseType: "arraybuffer", params: this.$http.adornParams({ 'url' : infoModel.projectIndexUrl }) }).then(({ data }) => { let bytes = new Uint8Array(data); let storeData = ""; let len = bytes.byteLength; for (let i = 0; i < len; i++) { storeData += String.fromCharCode(bytes[i]); } this.dialogImageUrlArray[0].url = "data:image/png;base64," + window.btoa(storeData); this.screenShotChange('', this.dialogImageUrlArray); // 隱藏上傳按鈕 });