基于element-ui完成表单中文件上传功能(单文件-多文件-下载)

前不久使用的时候发现element ui的el-upload还是有不少坑,单文件多文件上传因为后端约定的接口方式也有些不一样,后面又做了一下切片上传和文件下载,因此做一个总结

普通上传

在from中使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<el-form-item label="选择文件" prop="modelFile">
<el-upload
:with-credentials="true"
ref="uploadModel"
:file-list="modelForm.modelFile"
accept=".glb"
:on-change="getFileName"
multiple
:action="uploadAction"
:auto-upload="false"
:show-file-list="false"
:http-request="uploadFile"
>
<el-input placeholder="请选择文件" v-model="modelFileNames" suffix-icon="el-icon-upload2"></el-input>
</el-upload>
</el-form-item>

这里需求实现的效果如图,隐藏文件列表但是展示文件名,当点击下方时提交表单并上传文件

主要注意几个参数:

参数 说明 类型 可选值 默认值
with-credentials 支持发送 cookie 凭证信息 boolean / false
file-list 上传的文件列表, 例如: [{name: ‘food.jpg’, url: ‘https://xxx.cdn.com/xxx.jpg'}] array / []
action 必选参数,上传的地址 string / /
auto-upload 是否在选取文件后立即进行上传 boolean / true
http-request 覆盖默认的上传行为,可以自定义上传的实现 function / /
自定义的上传

这里采用完全自定义上传的方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
uploadModel() {
if (this.onlyOneFile) {
this.fileData = new FormData() // new formData对象
this.$refs.uploadModel.submit() // 提交调用uploadFile函数
let params = {
categoryId: this.modelForm.categoryId,
files: this.fileData
}
this.$store.dispatch('model/uploadModel', params).then(res => {
config.CallbackHandler(res).then(res => {
if (res.code === '200') {
// console
}
})
})
}
},
// 上传文件formData处理
uploadFile(file) {
this.fileData.append('files', file.file)
}

请求参数

默认上传

若不采用自定义上传,则直接调用this.$refs.upload.submit(),同时注意这几个参数:

参数 说明 类型 可选值 默认值
data 上传时附带的额外参数 object / /
name 上传的字段名 string / file
header 设置上传的请求头部 object / /

而且经测试多文件上传时element是多次请求而不是统一请求,因此建议多文件上传还是采用自定义的方式

分片上传

切片上传建议先阅读这个系列博客

简而言之,实现切片上传主要分为以下几步:

  • 通过MD5校验文件是否存在
    • 存在,秒传
    • 不存在,进入下面步骤
  • 前端切片
  • 服务端检验每个切片是否存在
  • 分片上传
  • 合并文件
上传组件的实现

基于上文博客,基于业务设计需求做了一定的暴力修改

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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
<template>
<div id="global-uploader">
<!-- 上传 -->
<uploader
ref="uploader"
:options="options"
:autoStart="false"
@file-added="onFileAdded"
@file-success="onFileSuccess"
@file-progress="onFileProgress"
@file-error="onFileError"
class="uploader-app"
>
<uploader-unsupport></uploader-unsupport>

<uploader-btn id="global-uploader-btn" :attrs="attrs" ref="uploadBtn">选择文件</uploader-btn>

<uploader-list v-show="panelShow">
<div class="file-panel" slot-scope="props" :class="{ collapse: collapse }">
<ul class="file-list" ref="uploader-file-list">
<li v-for="file in props.fileList" :key="file.id">
<uploader-file :class="'file_' + file.id" ref="files" :file="file" :list="true"></uploader-file>
</li>
<div class="no-file" v-if="!props.fileList.length"><i class="iconfont icon-empty-file"></i> 暂无待上传文件</div>
</ul>
</div>
</uploader-list>
</uploader>
</div>
</template>

<script>
import SparkMD5 from 'spark-md5'
import api from '@/common/api'
var loadingFileMap = {}
const statusMap = {
md5: {
text: '校验MD5',
bgc: '#fff'
},
merging: {
text: '合并中',
bgc: '#e2eeff'
},
success: {
text: '上传成功',
bgc: '#e2eeff'
},
transcoding: {
text: '转码中',
bgc: '#e2eeff'
},
paused: {
text: '暂停上传',
bgc: '#e2eeff'
},
failed: {
text: '上传失败',
bgc: '#e2eeff'
}
}
export default {
name: 'upload',
props: {
fileExt: Array
},
data() {
return {
options: {
target: api.getUrl('fileupload'),
singleFile: true,
chunkSize: '5120000',
fileParameterName: 'file',
maxChunkRetries: 3,
withCredentials: true, //带session
testChunks: true, //是否开启服务器分片校验
// 服务器分片校验函数,秒传及断点续传基础
checkChunkUploadedByResponse: function(chunk, message) {
let res = JSON.parse(message)
if (!res.status || loadingFileMap[chunk.file.fid]) {
return true
}
return (res.uploaded || []).indexOf(chunk.offset + 1) >= 0
},
query() {}
},
attrs: {
accept: this.fileExt
},
panelShow: false, //选择文件后,展示上传panel
collapse: false
}
},
computed: {
//Uploader实例
uploader() {
return this.$refs.uploader.uploader
}
},
methods: {
openUploader() {
if (this.$refs.uploadBtn) {
this.$refs.uploadBtn.$el.click()
}
},
onFileAdded(file) {
this.$emit('fileAdded', file)
this.panelShow = true
this.computeMD5(file)
},
// eslint-disable-next-line
onFileProgress(rootFile, file, chunk) {
// console.log(`上传中 ${file.name},chunk:${chunk.startByte / 1024 / 1024} ~ ${chunk.endByte / 1024 / 1024}`)
},
// eslint-disable-next-line
onFileSuccess(rootFile, file, response, chunk) {
// 分片服务端返回需要合并
// 如果文件存在 秒传
if (loadingFileMap[chunk.file.fid]) {
this.statusSet(file.id, 'success')
return this.$emit('fileSuccess', file)
}
this.statusSet(file.id, 'merging')
let param = {
ext: file.fileType,
fid: file.fid,
identifier: file.uniqueIdentifier,
filename: file.name
}
this.$store
.dispatch('model/mergeFile', param)
.then(res => {
if (res.status) {
this.$emit('fileSuccess', file)
this.statusSet(file.id, 'success')
} else {
this.$emit('fileSuccess', file)
this.statusSet(file.id, 'failed')
this.$message({
message: res.message,
type: 'error'
})
}
})
.catch(() => {
this.statusSet(file.id, 'failed')
})
},
// eslint-disable-next-line
onFileError(rootFile, file, response, chunk) {
this.statusSet(file.id, 'failed')
this.$emit('fileError', response)
// this.$message({
// message: response,
// type: 'error'
// })
},

/**
* 计算md5,实现断点续传及秒传
* @param file
*/
computeMD5(file) {
let fileReader = new FileReader()
// let time = new Date().getTime()
let md5 = ''

file.pause()
//开始计算md5
this.statusSet(file.id, 'md5')
//保护
this.protectComputeMd5(file.id, true)
let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunkSize = 102400000, // 以每片100MB大小来逐次读取
chunks = Math.ceil(file.size / chunkSize),
currentChunk = 0,
spark = new SparkMD5() //创建SparkMD5的实例

loadNext()
fileReader.onload = e => {
spark.appendBinary(e.target.result)
currentChunk += 1
if (currentChunk < chunks) {
loadNext()
} else {
md5 = spark.end()
let param = {
filename: file.name,
identifier: md5,
totalSize: file.size,
fileType: file.fileType
}
this.$store.dispatch('model/checkFile', param).then(res => {
this.statusSet(file.id, 'paused')
//取消保护md5
this.protectComputeMd5(file.id, false)
file.uniqueIdentifier = md5
// 添加额外的参数
this.uploader.opts.query = {
fid: res.data
}
if (!res.status) {
//秒传
loadingFileMap[res.data] = true
}
file.fid = res.data
file.resume()
})
}
}
function loadNext() {
let start = currentChunk * chunkSize,
end = start + chunkSize >= file.size ? file.size : start + chunkSize
// debugger
fileReader.readAsBinaryString(blobSlice.call(file.file, start, end))
}

fileReader.onerror = function() {
this.error('FileReader onerror was triggered, maybe the browser aborted due to high memory usage.')
}
},

/**
* 新增的自定义的状态: 'md5'、'transcoding'、'failed'
* @param id
* @param status
*/
statusSet(id, status) {
this.$nextTick(() => {
let _tag = this.$refs['uploader-file-list']
.getElementsByClassName('file_' + id)[0]
.getElementsByClassName('uploader-file-status')[0]
.getElementsByTagName('span')[0]
_tag.innerText = statusMap[status].text
})
},
// 保护md5计算
protectComputeMd5(id, status) {
this.$nextTick(() => {
let _tag = this.$refs['uploader-file-list'].getElementsByClassName('file_' + id)[0]
if (status) {
_tag.setAttribute('status', 'protect')
} else {
_tag.setAttribute('status', 'paused')
}
})
}
},
watch: {},
destroyed() {
this.$off('openUploader')
}
}
</script>
<style>
.uploader-list {
margin-top: 10px;
}
ul li {
list-style: none;
}
</style>
组件使用
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
<el-form size="mini" ref="form" :model="form" label-width="70px" label-position="right">
<el-form-item label="选择文件" prop="filename">
<el-input placeholder="请选择文件" v-model="form.filename" :disabled="true">
<template slot="append">
<upload class="upload-demo" @fileAdded="fileAdded" @fileSuccess="fileSuccess" @fileError="fileError">
</upload>
</template>
</el-input>
<span v-if="uploadStatus === 'UPLOADING'" class="uploadLoading"><i class="iconfont iconLoading"></i>上传中</span>
<span v-if="uploadStatus === 'FULFILLED'" class="uploadSuccess"><i class="iconfont iconSuccess"></i>上传成功</span>
<span v-if="uploadStatus === 'REJECTED'" class="uploadFail"><i class="iconfont iconFail"></i>{{ uoloadErrorMessage }}</span>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" size="mini" @click="handleSubmit">确定</el-button>
<el-button type="primary" size="mini" @click="visible = false" plain>取消</el-button>
</div>

<script>
export default {
data(){
retuen{
form: {},
uploadFile: {},
uploadStatus: 'PENDING' // PENDING--初始状态,UPLOADING--正在上传,FULFILLED--成功,REJECTED--失败
}
},
methods:{
// 开始添加文件
fileAdded() {
this.uploadStatus = 'UPLOADING'
console.log('开始上传')
},
// 上传成功
fileSuccess(file) {
this.uploadStatus = 'FULFILLED'
let fileName = file.name
let type = fileName.substr(fileName.lastIndexOf('.') + 1)
let name = fileName.split(`.${type}`).join('')
this.uploadFile = file
this.uploadFile._name = name
this.uploadFile._type = type
this.form.filename = name
console.log('上传成功')
},
// 上传失败
fileError(res) {
this.uoloadErrorMessage = res
this.uploadStatus = 'REJECTED'
console.log('上传失败')
},
// 确认导入资源
handleSubmit() {
let params = {
fileId: this.uploadFile.fid,
type: this.uploadFile._type
name: this.uploadFile._name
}
this.$store
.dispatch('model/addModel', params)
.then(res => { BusinessUtil.CallbackHandler(res) })
.then(() => {
this.visible = false
this.form = {
professional: '',
filename: ''
}
this.uploadStatus = 'PENDING'
this.uploadFile = {}
})
},
}
}
</script>
<style lang="scss">
.formDialog {
.el-input-group__append {
padding: 0;
}

.uploader-btn {
padding: 0 !important;
width: 84px;
height: 26px;
display: flex !important;
align-items: center;
justify-content: center;
border: none !important;
font-size: 12px !important;
color: #0065eb !important;
}

.uploader-list {
display: none !important;
}

.iconfont {
font-size: 12px !important;
}

.uploadLoading {
color: #0065eb;
}

.uploadSuccess {
color: #52c41a;
}

.uploadFail {
color: #ff4d4f;
}
}
</style>
最终效果

文件下载

下载为后端返回的二进制文件流,主要思路就是使用BlobFileReader对象,产生的二进制链接使用<a>标签的a.download方法下载,这里需要注意的是这样下载的文件默认是txt文件,需要手动指定文件类型

Blob构造函数返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成,具体展开见MDN

FileReader对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 FileBlob 对象指定要读取的文件或数据,详见MDN

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
handleDown(index, row) {
this.$store
.dispatch('model/downloadModel', row.id)
.then(res => BusinessUtil.CallbackHandler(res))
.then(res => {
const content = res.data
const blob = new Blob([content])
let reader = new FileReader()
reader.readAsText(blob, 'utf-8')
reader.onload = () => {
try {
let error = reader.result
let jsonError = JSON.parse(error)
this.$message({
message: jsonError.message,
type: 'error'
})
// Message.error(jsonError.message)
} catch (err) {
let a = document.createElement('a')
a.href = URL.createObjectURL(blob)
console.log(a.href)
a.download = `${row.name}.${row.type}`
a.target = '_blank'
a.click()
a.remove()
}
}
})
}