最近使用七牛上传的时候遇到了一点小问题:上传时开启七牛图片压缩,发现能够成功请求七牛上传接口但是没有触发complete导致不能获取回调,原因已经找到,因为七牛图片压缩之后的文件是Blob对象,直接上传的话七牛jdk会有问题,将压缩后的Blob对象转换成File对象就行了。
qiniu.compressImage(file, options).then(data => {
const observable = qiniu.upload(data.dist, key, token, putExtra, config)
const subscription = observable.subscribe(observer)
})
import * as qiniu from 'qiniu-js'
export default (file,type='image',token,domain)=>{
return new Promise((resolve,reject)=>{
const options = {quality: 0.92,noCompressIfLarger: true}
const config = {
useCdnDomain: true,
region: qiniu.region.z0,
chunkSize: 100,
forceDirect: true,
}
const putExtra = {
fname: file.name,
mimeType: [] || null
};
let key = new Date().getTime() + Math.random(1000) + file.name;
const upload = (f)=>{
let observable = qiniu.upload(f, key, token, putExtra, config);
observable.subscribe({
next: () => {},
error: (err) => {
console.log(err);
reject(err)
},
complete: (res) => {
const resFileObj = {
file_suffix: f.name.replace(/.+\./, ""),
real_url: `${domain}/${res.key}`,
cover_url: type=='video' ? `${domain}/${res.key}?vframe/jpg/offset/1` : ''
}
resolve(resFileObj)
}
})
}
if(type=='image'){
qiniu.compressImage(file, options).then(data=>{
const blobToFile = (data) => new File(
[data], file.name,
{type: file.type, lastModified: Date.now()}
)
upload(data.dist instanceof File ? data.dist : blobToFile(data.dist))
})
}else{
upload(file)
}
})
}
|