前端实现阿里云oss直传-进度条
目录
前端实现阿里云oss直传 进度条
前端实现阿里云oss上传 进度条
阿里云oss内部配置这里不再赘述 需要请搜索百度
桶内跨域配置
重要 :注意要暴露headers
实例化
const OSS = require('ali-oss')
const client = new OSS({
region: 'oss-cn-beijing', // oss存储地域 创建桶的时候选择的地域
accessKeyId: '入口id', // 入口id id和秘钥前往accesskey 进行配置
accessKeySecret: '秘钥', // 秘钥
bucket: 'hrdemo', // 存储通 创建的桶名
secure: true
})
上传代码
此处较为重要
在没有设置parSize的时候上传文件 发现progress 打印的值percentage 等了很长时间依旧是显示了个0 和 1
检查后发现 每传输完一个分片 进度条会走一个百分比 不设置的话由于partsize过大 可能导致很长时间进度条都看不到效果
// img 文件夹下 obj.file.name 文件的名字 obj.file文件对象
client.multipartUpload('img/' + obj.file.name, obj.file,
{
// 进度条的配置项
progress: function(percentage) { // 获取进度条的值
console.log(percentage)
// console.log(p * 100)
this.percent = percentage * 100
},
// 每传输完一个分片 进度条会走一个百分比 不设置的话由于partsize过大 可能导致很长时间进度条都看不到效果
partSize: 102400 // 指定上传的每个分片的大小,范围为100 KB~5 GB。单个分片默认大小为1 * 1024 * 1024(即1 MB)
}
).then(response => {
console.log(response)
if (response.res.status === 200) {
console.log('上传了')
this.imageUrl = response.url // 把上传后的地址给img
this.showProgress = false
}
}).catch(function(err) {
console.error('error: ', err)
})
put方式
该方式没有回调 如果有进度条的需求 选择multipartUpload方法上传文件
client.put('img/' + obj.file.name, obj.file).then(response => {
console.log(response)
if (response.res.status === 200) {
console.log('上传了')
this.imageUrl = response.url // 把上传后的地址给img
this.showProgress = false
}
}).catch(function(err) {
console.error('error: ', err)
})
上传后的效果图
图片位于桶根目录下的img文件中
可参考的博客地址: