预览已经上传的图片要点: window.URL.createObjectURL(new Blob([res])) 上传图片的要点: const formData = new FormData() formData.append('file', file.file) 完整案例:
1、预览图片: <a-form-item class="ef-item ef-i-w100" label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback > <template> <a-auto-complete placeholder="请输入姓名" allowClear @search="handleSearch" @change="handleSelect($event,`${item.id}`)"> <template slot="dataSource"> <a-select-option v-for="(it, index) in result" :key="index" :value="it.id"> {{ it.policeName }} </a-select-option> </template> </a-auto-complete> </template> <a-input v-show="false" v-decorator="['policeName', {rules: [{ required: true, validator: (rule, value, callBack)=>{ var Reg=/^[\u2E80-\u9FFF]+$/;//Unicode编码中的汉字范围 if(!value){ callBack('请输入姓名') }else if(!Reg.test(value)) { callBack('输入姓名不合法') } callBack() } }] } ]" ></a-input> </a-form-item> <a-form-item class="ef-item ef-i-w50 phones" label="照片" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback > <div class="ant-upload-preview" @click="edit(item.id)" v-decorator="['poliecePhoto']"> <div class="mask"> <a-icon type="plus" /> </div> <img :src="option[item.id].img == null ? option[0].img :option[item.id].img"/> </div> </a-form-item> //根据id预览图片 handleSelect(value,index) { if(this.result == null && this.result.length === 0){return} const filterValue = this.result.filter(item => item.id === value) const { form } = this.formList[index] if(filterValue!= null && filterValue.length > 0) { const record = filterValue[0] form.setFieldsValue({ policeName: record.policeName, ... }) //预览照片 this.businessEscortPreview(record, index) } else { form.setFieldsValue({ policeName: '', .... }) } }, /** * 获取图片并转为链接 */ businessEscortPreview(record, index) { businessEscortPreview({ id: record.poliecePhoto }) .then((res) => { const src = window.URL.createObjectURL(new Blob([res])) this.option[index].img = res.byteLength <= 208 ? '/default_mj_photo.png' : src }) .catch((err) => { this.$message.error('预览错误:' + err.message) }) }, 2、扩展知识:上传图片 //上传图片 大致思路 <a-upload name="file" ref="files" :multiple="false" :file-list="fileList" :beforeUpload="beforeUpload" :remove="handleRemove" @change="handleChangeFile" @preview="handlePreview" > <a-button class="buttons" :disabled="disableType"> 上传附件 </a-button> </a-upload> //上传当前图片,每次校验完毕及时上传,需要使用formData 方式 handleChangeFile(file) { if (this.fileStatus != 'removed') { const { $message } = this const formData = new FormData() formData.append('file', file.file) this.fileList = file.fileList sysFileInfoUpload(formData) .then((res) => { if (res.code == 200) { $message.success('上传成功') //res.data 即为上传图片生成的id this.adjunctArr.push(res.data) this.adjunct = this.adjunctArr.join(',') this.$emit('adjunctFun', { adjunct: this.adjunct, }) } }) .catch((err) => { $message.error('上传失败' + err.message) }) } },