使用传统的input框,实现上传文件的方式,如图效果:
如何进行文件格式的校验,代码如下:
-------------html部分-----------
<div v-if="!readOnly" class="upload-btn" @click="chooseTrigger('upload')">添加附件</div>
<input type="file" ref="uploadInput" style="display: none" @change="uploadTrigger" />
-------------js部分-------------
/* 校验部分 */
uploadTrigger() {
let files = this.$refs["uploadInput"].files;
// 限制的格式范围
const txtname = ".zip|.rar|.html|.doc|.docx|.ppt|.wps|.pdf|.xls|.xlsx|"
// 校验
var extName = files[0].name.substring(files[0].name.lastIndexOf(".")).toLowerCase();//(把路径中的所有字母全部转换为小写)
// 判断
if(txtname.indexOf(extName+"|") == -1) {
this.$Message.error('请上传正确的文件格式!如:' + txtname);
return
}
},
补充:
如何删除type=file时,已经上传的文件:this.$refs.[xxx].value = null
或者 this.$refs.xxx = null
-----------------------更新-----2023.08.01---------------------------------------------------------------------------------------------------------------------------------------
解决input框上传写在form表单中,无法清除校验提示的问题
在改以前项目代码时发现上传时通过input的type=file实现的,在表单校验的时候也遇到了问题,如图
因为是写在表单中,所以进行了rules校验,但是,这个校验触发后即使上传文件,校验也无法消失了
于是参考了iview源码,打印了一下this.$refs.productData.fields
又打印了一下,我要清除校验的绑定input的这个字段prop
const fields = this.$refs.productData.fields
fields.forEach((item) => {
if (item.prop === 'fileNote') {
console.log(item)
}
})
得到的打印结果如下图:
发现了几个重要的api, 就是上图框住的几个
iview form清除校验状态的实现
其实就是把 formItem 的两个属性值进行了修改,
validateDisabled 是否校验
validateState 展示状态(校验错误时此处值为 ‘error’)
validateMessage 错误提示文字
(ps:可以自己打印一下康康,我截图不是打印的全部api)
所以,要想清除校验,就是调用字段的resetField()方法,或者吧以上几个属性改对即可 我这边采用第一种方式
完整代码:
<Form ref="productData" :model="productData" :label-width="170" label-colon>
.......
<FormItem label="上传" prop="fileNote" :rules="ruleValidate['fileNote']">
<Button class="file-btn">
<span class="file-real">选择文件</span>
<input placeholder="请选择" type="file" @change="handleKeyUpload" ref="file" id="fileId" />
</Button>
<span>{
{
keyFileUrl}}</span>
</FormItem>
......
</Form>
js部分
handleKeyUpload (e) {
// 上传文件后清除校验提示(重点就是这里)
const fields = this.$refs.productData.fields
fields.forEach((item) => {
if (item.prop === 'fileNote') {
item.resetField() // 重点!!!!!
}
})
// 获取用户选择的文件
const files = this.$refs.file.files
// 限制的格式范围
// const txtname = '.png,.exe,'
// // 校验
// var extName = files[0].name.substring(files[0].name.lastIndexOf('.')).toLowerCase() // (把路径中的所有字母全部转换为小写)
// // 判断
// if (txtname.indexOf(extName + ',') === -1) {
// this.$Message.error('请上传正确的文件格式!如:' + txtname)
// return
// }
this.keyFileUrl = e.target.value
this.getBase64File(files[0])
return false
},
// 把文件转化为base64
getBase64File (file) {
const reader = new FileReader()
reader.readAsDataURL(file)
this.productData.fileNote = null
// 注意此方法是异步的 若要卸载外面需要将其改写为promise
reader.onload = (e) => {
this.productData.fileNote = e.target.result // 将base64编码赋值给对象
this.productData.fileNote = encodeURIComponent(this.productData.fileNote.substring(this.productData.fileNote.indexOf(',') + 1))
}
},