vue+oss+element上传拿走不谢
程序员文章站
2022-07-14 21:26:35
...
vue+oss+element上传拿走不送
为了前端小伙伴少走一些弯路
最近公司业务有使用oss的业务 以下代码是基于oss 进行封装的代码
const OSS = require('ali-oss')
// 'aliyun_oss_bucket'=>"mrstatic"
export const uploadOss = function (file, onprogress) {
return new UploadFile(file, onprogress)
}
class UploadFile {
config = {
region: 'oss-cn-beijing', // your region
accessKeyId: '', // your accessKeyId
accessKeySecret: '', // accessKeySecret
bucket: '' //
}
tempCheckpoint = null
client = null
resumeclient = null
onprogress = null
file = null
objectkey = null
constructor (file, onprogress) {
// super(this)
this.file = file
onprogress && (this.onprogress = onprogress)
this.client = new OSS(this.config)
this.resumeclient = new OSS(this.config)
this.objectkey = new Date().getTime() + file.name
}
upload () {
const _this = this
console.log('upload')
return new Promise(async function (resolve, reject) {
try {
let result = await _this.client.multipartUpload(_this.objectkey, _this.file, {
progress: async function (p, checkpoint) {
console.log('checkpoint', checkpoint)
// 断点记录点。 浏览器重启后无法直接继续上传,需用户手动触发进行设置。
if (checkpoint) {
_this.onprogress({
percent: checkpoint.partSize / checkpoint.fileSize
})
}
_this.tempCheckpoint = checkpoint
},
meta: { year: 2019, people: 'test' },
mime: 'video/mp4'
})
_this.onprogress({
percent: 100
})
console.log(result)
resolve(result)
} catch (e) {
reject(e)
console.log(e)
}
})
}
resumeUpload () {
const _this = this
return new Promise(async function (resolve, reject) {
try {
let result = await _this.resumeclient.multipartUpload(_this.objectkey, _this.file, {
progress: async function (p, checkpoint) {
// 断点记录点。 浏览器重启后无法直接继续上传,需用户手动触发进行设置。
if (checkpoint) {
_this.onprogress({
percent: checkpoint.partSize / checkpoint.fileSize
})
}
_this.tempCheckpoint = checkpoint
},
checkpoint: _this.tempCheckpoint,
meta: { year: 2019, people: 'hanjixin' },
mime: 'video/mp4'
})
_this.onprogress({
percent: 100
})
resolve(result)
} catch (e) {
reject(e)
console.log(e)
}
})
}
cancel () {
this.client.cancel()
this.resumeclient.cancel()
}
}
element 上传部分
我看了一下官网只提供了http-request (覆盖默认的上传行为,可以自定义上传的实现 )
但是没有过多的详细介绍
- k看了一下源码arguments 只返回了 下面的对象
const options = {
headers: this.headers,
withCredentials: this.withCredentials,
file: rawFile,
data: this.data,
filename: this.name,
action: this.action,
onProgress: e => {
this.onProgress(e, rawFile);
},
onSuccess: res => {
this.onSuccess(res, rawFile);
delete this.reqs[uid];
},
onError: err => {
this.onError(err, rawFile);
delete this.reqs[uid];
}
};
- 里面继续看 e 需要传一个对象
file.percentage = ev.percent || 0;
// ev 就是 e 这个对象
// { percent: number }
所以e 要穿的对象必须包含 percent 属性
上一篇: 多张Echart图表根据浏览器大小自适应
下一篇: OSS分块上传实例