input type="file" 原生属性
-
vue中用法:
图一(打开前):
image.png
图二(打开后):
image.png
代码:
1.用于自定义展示input
<el-input
type="text"
size="mini"
v-model="excelName"
style="width:300px;marginRight:20px;"
></el-input>
2.input file本体,隐藏展示
<input
type="file"
id="uploadExcel"
ref="uploadExcel"
v-show="false"
accept=".xls, .xlsx, .excel"
@change="readExcel"
/>
3.触发打开文件按钮
<div type="text" @click="importExcel" class="btnText uploadBtn">浏览</div>
4.发起axios请求按钮
<el-button round class="bigBtn" @click="gmDrSure" size="medium ">批量导入</el-button>
method:
//打开文件
importExcel () {
this.$refs.uploadExcel.click();
},
//读取文件
readExcel (event) {
let fileList = event.target.files;
this.excelName = fileList[0].name
this.excelFile = this.$refs.uploadExcel.files[0];
// console.log(fileList, this.excelFile)
// const loadinginstace = Loading.service({ fullscreen: true, background: 'rgba(0, 0, 0, 0.1)', text: '文件读取中,请稍等' })
// //
// let reader = new FileReader()
// reader.readAsDataURL(fileList[0])
// reader.onloadstart = function () {
// console.log('ss')
// }
// reader.onload = function (e) {
// // console.log(reader.result)
// loadinginstace.close();
// }
},
//发送请求
gmDrSure () {
this.uploadDialog = false
let formData = new FormData()
formData.append('file', this.excelFile);
console.log('formData', formData)
if(this.excelName==='' ) return this.$message.warning('请先选择excel文件')
//上传excel
upload.uploadMember(formData).then(res => {
console.log(res)
if (res.result == 0) {
this.$message.success('上传成功~')
this.getMemberList()
let obj=this.$refs.uploadExcel
obj.outerHTML=obj.outerHTML;
this.excelFile = ''
this.excelName = ''
}
})
},
总结:
- 请求头headers设置:
"Content-Type": "multipart/form-data"
- 主要使用input原生属性file,通过
new FormData()
新建和append
添加
let formData = new FormData()
formData.append('file', this.excelFile);
- 针对文件,通过
console.log('formData', formData)
打印不出内容,一般会显示空对象,通过Network可以查看参数
- console.log() formData
-
Form Data(view parsed):
view parsed -
Form Data(view source):
view source -
清除input file
let obj=this.$refs.uploadExcel
obj.outerHTML=obj.outerHTML;
- 下载模板
//下载模板
handleDownload () {
window.open('https://url/导入会员模板.xls')
}
网友评论