element 上传文件时,选择多个文件会多次调用接口
template代码如下:
<el-upload
class="upload-file"
ref="uploadFile"
:limit="limit"
multiple
show-file-list
:http-request="uploadFile"
:on-change="onChange"
:data="dataObj"
:before-upload="beforeuploadFile"
action="123"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button type="primary" size="mini" :loading="btnLoading"><i class="el-icon-upload2"></i>导入文件包</el-button>
</el-upload>
js代码如下:
const OSS = require('ali-oss') // 文件上传至oss
export default {
data () {
return {
limit: 10,
fileList: [], // 文件列表
files: [], // 当前选中的files
btnLoading: false,
dataObj: { // 根据需要设置
region: 公司oss域名',
accessKeyId: 'oss的key',
accessKeySecret: '',
bucket: ''
},
beforeUrl: '', // 可以不设置,方便文件分类
}
},
methods: {
onChange (file, fileList) {
this.files = fileList
},
beforeuploadFile (file) {
this.client = new OSS(this.dataObj)
// const isJPG = file.type === 'image/jpeg';
const isLt50M = file.size / 1024 / 1024 < 50
// if (!isJPG) {
// this.$message.error('上传头像图片只能是 JPG 格式!');
// }
if (!isLt50M) {
this.$alarm.showWarning('上传文件大小不能超过 50MB!')
}
return isLt50M
},
uploadFile (file) { // 上传
this.btnLoading = true
const that = this
var userinputName = file.file.name
const fileName =
that.beforeUrl +
Math.random().toString(36).substr(2) + '_' + userinputName
async function put () {
try {
// object-name可以自定义为文件名(例如file.txt)或目录(例如abc/test/file.txt)的形式,实现将文件上传至当前Bucket或Bucket下的指定目录。
const result = await that.client.put(fileName, file.file)
var index = userinputName.lastIndexOf('/')
userinputName = userinputName.substring(
index + 1,
userinputName.length
) // 文件名
const arr = userinputName.split('.')
arr && arr.splice(arr.length - 1, 1)
const name = arr && arr.join('.') // 后端需要没有后缀的文件名
that.fileList.push({ name: userinputName, fileName: name, url: result.url })
if (that.fileList.length === that.files.length) {
const files = [] // 需要上传的数组
that.files.forEach(item => {
that.fileList.forEach(data => {
if (item.status === 'ready' && item.name === data.name) {
files.push(data)
}
})
})
that.addTaskFilesNotaskModeAjax(files) // 调用后端接口
}
} catch (e) {
console.log(e)
that.btnLoading = false
}
}
put()
},
addTaskFilesNotaskModeAjax (fileList) { // 批量导入后端接口
const files = fileList.map(item => ({ fileName: item.fileName, uploadFileName: item.name, uploadFileUrl: item.url }))
const params = {
workId: this.workId,
files: files
} // 后端接口参数
addTaskFilesNotaskMode(params).then(res => {
if (res.code === 0) {
this.$alarm.showSuccess(res.msg)// 提示信息
// 清空默认值
this.files = []
setTimeout(() => {
this.btnLoading = false
}, 500)
}
}).catch(err => {
console.log(err)
this.btnLoading = false
// 清空默认值
this.files = []
})
},
handleExceed (files, fileList) {
this.$message.warning(`当前限制选择 ${this.limit} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
}
}
}
###主要流程为文件多选上传至oss, oss返回url,最后获取所有上传的url数组,再传给后端,避免多次调用后端接口