input type="file" 原生屬性
-
vue中用法:
圖一(打開(kāi)前):
圖二(打開(kāi)后):
代碼:
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.觸發(fā)打開(kāi)文件按鈕
<div type="text" @click="importExcel" class="btnText uploadBtn">瀏覽</div>
4.發(fā)起axios請(qǐng)求按鈕
<el-button round class="bigBtn" @click="gmDrSure" size="medium ">批量導(dǎo)入</el-button>
method:
//打開(kāi)文件
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: '文件讀取中,請(qǐng)稍等' })
// //
// let reader = new FileReader()
// reader.readAsDataURL(fileList[0])
// reader.onloadstart = function () {
// console.log('ss')
// }
// reader.onload = function (e) {
// // console.log(reader.result)
// loadinginstace.close();
// }
},
//發(fā)送請(qǐng)求
gmDrSure () {
this.uploadDialog = false
let formData = new FormData()
formData.append('file', this.excelFile);
console.log('formData', formData)
if(this.excelName==='' ) return this.$message.warning('請(qǐng)先選擇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 = ''
}
})
},
總結(jié):
- 請(qǐng)求頭headers設(shè)置:
"Content-Type": "multipart/form-data"
- 主要使用input原生屬性file,通過(guò)
new FormData()
新建和append
添加
let formData = new FormData()
formData.append('file', this.excelFile);
- 針對(duì)文件膜毁,通過(guò)
console.log('formData', formData)
打印不出內(nèi)容,一般會(huì)顯示空對(duì)象愤钾,通過(guò)Network可以查看參數(shù)
-
console.log()
-
Form Data(view parsed):
-
Form Data(view source):
清除input file
let obj=this.$refs.uploadExcel
obj.outerHTML=obj.outerHTML;
- 下載模板
//下載模板
handleDownload () {
window.open('https://url/導(dǎo)入會(huì)員模板.xls')
}