upload-xlsx.vue
3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<template>
<div @click="handleClick" style="display: inline-block;">
<input ref="input" type="file" accept=".xlsx" @change="handleChange">
<slot></slot>
</div>
</template>
<script>
import request from 'axios';
import _ from 'lodash';
export default {
name: 'upload-xlsx',
props: {
action: {
type: String,
default() {
return '/upload/xlsx';
}
},
onSuccess: {
type: Function,
default() {
return {};
}
},
onError: {
type: Function,
default() {
return {};
}
},
onProgress: {
type: Function,
default() {
return {};
}
},
onChange: {
type: Function,
default() {
return {};
}
},
data: {
type: Object,
default() {
return {};
}
}
},
data() {
return {
files: null
};
},
methods: {
handleClick() {
this.$refs.input.click();
},
handleChange(e) {
this.files = e.target.files;
this.onChange(this.files);
},
upload(data) {
let files = this.files;
if (!files) {
return Promise.reject();
}
let postFiles = Array.prototype.slice.call(files);
postFiles = postFiles.slice(0, 1);
if (postFiles.length === 0) {
return Promise.reject();
}
Object.assign(this.data, data);
return this.post(postFiles[0], this.data);
},
clear() {
this.files = null;
},
post(file, params) {
let _this = this;
let config = {
onUploadProgress(processEvent) {
_this.onProgress(processEvent);
}
};
let data = new FormData();
data.append('file', file);
if (!_.isEmpty(params)) {
_.each(params, (v, k) => {
data.append(k, v);
});
}
return request.post(this.action, data, config)
.then((result) => {
_this.onSuccess(result.data);
})
.catch((err) => {
_this.onError(err);
});
}
}
};
</script>
<style lang="scss" scoped>
input[type="file"] {
display: none;
}
</style>