vue 中 js寫上傳excel表格
阿新 • • 發佈:2019-01-24
在頁面建立一個選擇檔案的按鈕,通過按鈕點選觸發chooseFile函式來模擬input[type=’file’]點選選擇檔案事件。監聽input[type=’file’]的onchange事件,來獲取選中檔案物件,再通過點選確認匯入按鈕觸發upFile函式來實現檔案的非同步上傳。複製大佬的程式碼,只是存下來方便以後檢視大佬的帖子點我
<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('.');
if (arr[1] !== 'xls' && arr[1] !== 'xlsx') {
this.$toast.center('檔案格式錯誤!');
return;
}
let fileData = new window.FormData();
fileData.append('file', this.attenceFile)
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)
this.$toast.center(response.message)
} else {
let error = this.$emit('upload-error', xhr)
if (error !== false) {
this.$toast.center(xhr.statusText)
}
}
}
}
}
}
}
</script>