問題:表單中包含上傳圖片的功能,相應的接口參數只接受 URL(string類型)
解決方法:獲取input中的file后,調用上傳圖片的接口(后台將圖片保存在文件服務器,返回url地址)
// 實際顯示的圖片 <img class="ad-img-wrap" :src="form.imgUrl" @click="clickImage"> <input type="file" @change="changeImgHandler($event)" ref="adImg" style="display: none;" accept="image/*"> changeImageHandler () { this.$refs.adImg.dispatchEvent(new MouseEvent('click')) } changeImgHandler (e) { let fileName = this.$refs.adImg.value this.form.imgInputVal = fileName let list = fileName.split('.') let type = list[list.length - 1] let flag = false // imgFormat 為所有圖片類型的數組 for (let i = 0; i < imgFormat.length; i++) { if (imgFormat[i] === type) flag = true } if (!flag) { this.$message({ message: '請選擇圖片', type: 'warning' }) return false } this.form.imgHasChanged = true this.form.imgFile = e.target.files[0] // 此處接受到 file 文件 } // 調用方法 asnyc submit() { const formData = new FormData() // 上傳文件接口要求的參數名為 file formData.append('file', that.form.imgFile) // API.uploadFile 為接口地址 let ret = await that.$http.post(API.uploadFile, formData) }
