前言:同事问我如何实现excel文件上传,她自己照着element-ui的文档没有成功,脑袋都炸了,加上咱老郑也是热心人,更何况女同事长得好看,于是我三下五除二就写了一个demo,十分钟后,她告诉我已经做好了,希望我多写一些这样的教程,索性我就把它简单整理了一下发布出来,希望能够帮到你,代码中js部分需要根据你的实际情况改动,其他地方按我的就行,此外我默认你使用的是element-ui ,请知悉
1. 添加上傳excel按鈕
<el-col :span="6">
<el-button class="main-top-button" type="warning" plain @click="upload()" style="margin-left:-2px;">上傳EXCEl
</el-button>
</el-col>
2. 在data()中設置初始化值
uploadFormVisible:false,
result:'',
fileName:'未选择文件',
fileList:[],
3. 在頁面中引入上傳彈框
<div style="width:90%;">
<el-dialog title="上傳頁面" :visible.sync="uploadFormVisible" width="200" :before-close="handleClose" :close-on-click-modal="false" append-to-body>
<div style="dispaly:flex;flex-direction:column;justify-content:center;">
<div>
若无模板,請先<span class="downSpan" @click="downLoadExcel()" style="color:blue;cursor:pointer;">下載</span>模板,再上傳Excel表格
</div>
<div>
<el-upload class="upload-demo" ref="upload" action="doUpload" :limit="1" :file-list="fileList" :before-upload="beforeUpload"
style="width:300px;float:left;">
<el-button slot="trigger" class="main-top-button del-btn" type="primary" plain >選擇文件</el-button>
<div class="el-upload-list__item-name" style="line-height: 40px;">{{fileName}}</div>
</el-upload>
</div>
<div style="height: 100px;width: 230px;">
<el-button class="main-top-button del-btn" type="primary" plain style="margin-top: 10px;float: left;" @click="submitUpload()">上传</el-button>
<div style="line-height: 60px;">{{result}}</div>
</div>
</div>
</el-dialog>
</div>
4. 在methods中添加下面的函數
handleClose(done){
done();
this.fileName='未选择文件'
},
submitUpload(){
if(this.fileName=="未选择文件"){
this.$alert("請選擇文件")
}else{
var file = new FormData();
//修改點1:根據參數修改
file.append('后台给你的文档中的参数', 你要给他的值);
//eg: file.append('changeFlow', this.addForm.changeFlow);
file.append('file',this.files);
let requestConfig = {
headers: {
'Content-Type': 'multipart/form-data'
},
}
this.result="上傳中...";
//修改點2:
// http://那你的後台ip:端口號/你的後台映射
this.$http.post('/upload', file, requestConfig)
.then(res => {
alert(res.data.message);
this.result="";
this.fileName="未选择文件";
this.uploadFormVisible=false;
});
}
},
beforeUpload(file) {
/* debugger */
this.files = file;
// const extension = file.name.split('.')[1] === 'xls'
const extension2 = file.name.split('.')[1] === 'xlsx'
const isLt2M = file.size / 1024 / 1024 < 5
if (!extension2) {
this.$message.warning('上传模板xlsx格式!')
return
}
if (!isLt2M) {
this.$message.warning('上传模板大小不能超过 5MB!')
return
}
this.fileName = file.name;
return false // 返回false不会自动上传
},
//如果你不需要下載模板,可以忽略
downLoadExcel(){
//把文件模板放在項目static目錄下 "/服務器上文件夾名/static/文件名.xlsx"
// 服务器上: window.open("/换成你的文件夹/static/book.xlsx")
//本地
window.open("/static/book.xlsx")
},
upload(){
this.uploadFormVisible=true;
},