vue上傳圖片并預覽
1.首先,<input type="file" />的上傳附件比較丑,所以我先將附件的樣式做了調整,如下:

這是HTML的代碼:
<div class="fileBox"> <span class="fileinput-button"> <img :src="srcOthers" alt="" width="100px" height="100px"> <span>點擊上傳</span> <input type="file" style="width: 100px;height: 100px;" @change="getFileOthers"> </span> </div> <div class="fileBox-word"> <span class="fileinput-word">合同及其他掃描件上傳</span> </div>
CSS樣式代碼:
<style scoped> .fileBox{ width: 100%; height: 112px; display: flex; flex-direction: row; justify-content: space-around; flex-wrap: wrap; } .fileBox-word{ width: 100%; height: 30px; display: flex; flex-direction: row; justify-content: space-around; flex-wrap: wrap; } .fileinput-button { width: 100px; height: 100px; float: left; display: flex; margin-top: 10px; line-height: 150px; position: relative; display: inline-block; overflow: hidden; color: #ccc; border: 1px solid #ccc; background: url(../../assets/img/addUpload.png) no-repeat; background-position: center 20px; } .fileinput-button input{ position: absolute; left: 0px; top: 0px; opacity: 0; -ms-filter: 'alpha(opacity=0)'; } .fileinput-word{ display: flex; width: 100px; text-align: center; float: left; margin-top: 10px; position: relative; display: inline-block; overflow: hidden; color: #666; font-size: 14px; } </style>
最后就是JS代碼:
methods: { getFileOthers (e) {//附件預覽----合同及其他掃描件 let _this = this var files = e.target.files[0]; console.log(e.target.files[0]); if (!e || !window.FileReader) return // 看支持不支持FileReader let reader = new FileReader() reader.readAsDataURL(files) // 這里是最關鍵的一步,轉換就在這里 reader.onloadend = function () { _this.srcOthers = this.result } }, },
這樣上傳附件并且可以預覽就實現了

浙公網安備 33010602011771號