参考地址:
https://blog.csdn.net/john_xiaoweige/article/details/81392110
本节中的注意点:
this.$refs.attenceInput.click(); 点击a按钮,相当于点击了按钮B本身哦!
input type=”file“ change事件只执行一次的问题 HTML:<input id="file", type="file" onchange="upload()" ref="referenceUpload" /> 回调成功方法里:this.$refs.referenceUpload.value = null; 否者成功后不能够进行二次导入哈!
<template> <div class="upload-panel"> <div class="panel-heading">考勤导入</div> <div class="panel-body"> <p><strong>注意事项:</strong><br>1、导入文件格式:.xls,.xlsx<br>2、文件命名规则“年月名”,如:“201705运维部考勤”></a></p> <p style="margin-top:10px;"><strong>考勤导入:</strong><a class="btn btn-primary btn-xs " @click="chooseFile">选择文件</a></p> <p>已选择文件:<em style="color:red; font-style:normal;">{{attence}}</em></p><p>{{info}}</p> <input type="file" style="display:none" name="attence" @change="changeFile($event)" ref="attenceInput" /> </div> <div class="panel-footer"> <a class="btn btn-primary btn-md" @click="upFile">确认导入</a> </div> </div> </template> <script> export default { name: 'Upload', data () { return { attence: '', attenceFile: {} } }, methods: { chooseFile () { this.$refs.attenceInput.click(); }, changeFile (e) { this.attence = e.target.files[0].name; this.attenceFile = e.target.files[0]; }, upFile () { let filename = this.attenceFile.name; let arr = filename.split('.');//这里这样还有点问题 如果别人是2010.23.34.xls这样的命名会出问题的 if (arr[1] !== 'xls' && arr[1] !== 'xlsx') { alter('文件格式错误!'); return; } let fileData = new window.FormData(); fileData.append('file', this.attenceFile);//file参数名。this.attenceFile是参数内容 // fileData.append('参数key', '内容value'); let xhr = new window.XMLHttpRequest(); xhr.open('POST', 'http://localhost:999/base/upload', true); xhr.send(fileData); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { let response = JSON.parse(xhr.response) console.log(response ) this.$refs.attenceInput.value = "";//这样才可以进行二次导入 } else { //导入失败的情况 this.$refs.attenceInput.value = "";//这样才可以进行二次导入 } } } } } } </script>