oss使用分片直传大文件

首先要先安装oss插件

npm install ali-oss

然后倒入oss插件,可以全局也可局部,我用的是局部

import OSS from 'ali-oss'

在用oss直传大文件的时候会出现浏览器崩溃的情况,针对这种情况,可使用分片上传

分片上传时,可能会出现以下情况

若出现上述情况,需要在oss中 要在跨域设置里面的暴露 Headers增加一条ETag,然后就可以正常上传了

 

uploadOssFile (data) {

var urlStr = this.upLoadAvatarOss(data)

console.log(this.ossData, urlStr)

},

async upLoadAvatarOss (e) {

const _this = this

_this.tableLoading = true

var file = e.file

var reader = new FileReader()

reader.readAsArrayBuffer(file)

return new Promise((resolve, reject) => {

reader.onload = function (event) {

const client = new OSS({

region: _this.ossData.region,

accessKeyId: _this.ossData.key,

accessKeySecret: _this.ossData.secret,

bucket: _this.ossData.bucket

})

let d = new Date()

let dArr = d.toLocaleDateString().split('/')

for (let index = 0; index < dArr.length; index++) {

if (index > 0 && dArr[index].length < 2) {

dArr[index] = '0' + dArr[index]

}

}

const obj = new Date().getTime() // 时间戳

const key = 'oss/' + 'project_' + _this.ossData.project_id + '/common/' + dArr.join('') + '/' + d.getTime() + '_' + file.name.split('.').join(obj + '.')

async function multipartUpload () {

_this.tableLoading = true

try {

let result = await client.multipartUpload(key, file, {

progress: function (percentage) {

console.log(percentage)

let fileloadingNum = Math.ceil(percentage * 100) + '%'

_this.tableText = '已上传' + fileloadingNum

},

meta: {

year: 2019,

people: 'multipartUpload'

}

})

console.log(result)

let head = await client.head(key)

console.log(head)

let data = {}

data.uploadFile = '/' + result.name

data.fileSize = file.size

data.suffix = file.name.substr(file.name.lastIndexOf('.') + 1, file.name.length)

data.project_id = _this.ossData.project_id

data.id = _this.getCurrentId()

data.name = file.name

_this.addFileAjax(data)

if (result.res.statusCode === 200) {

e.onSuccess(result)

return result

} else {

e.onError('上传失败')

}

} catch (e) {

// 捕获超时异常

if (e.code === 'ConnectionTimeoutError') {

console.log('Woops,超时啦!')

// do ConnectionTimeoutError operation

}

console.log(e)

}

}

return multipartUpload()

}

})

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值