项目里有这样一个bug
使用react-native-ay-image-picker按顺序选择多图时
把多个图片上传到七牛云 拿到七牛返回的url 这里有个问题
就是使用react-native-qiniu-hm上传到七牛 其实是异步上传每张图片 这样就不能保证返回的图片顺序就是上传的图片顺序 图片有大有小
要求 上传什么顺序 返回什么顺序
解决:使用rn的async和await解决问题
代码如下:
/**
* 图片上传七牛云~发表动态
*/
async dealWithImage(images) {
const {type, cid} = this.props.navigation.state.params;
LoadingUtil.showLoading();
for (let i = 0; i< images.length; i++) {
let key = 'publish' + "/" + new Date().getTime() + i + '.jpg';
let formInput = {
key: key,
};
putPolicy.scope = scope + ":" + key;
let uptoken = putPolicy.token();
await Rpc.uploadFile(images[i], uptoken, formInput).then(data => {
console.log(CDN_DOMAIN + key);
this.state.imageUrls.push(CDN_DOMAIN + key);
}).catch((error) => {
console.log("upload error:" + error);
});
}
LoadingUtil.dismissLoading();
let noticeParams = {
title: this.state.title,
};
let topicParams = {
images: this.state.imageUrls,
};
this.props.createBlogRequest({
...type === 'notice' ? noticeParams : topicParams,
content: this.state.content,
cid: cid,
state: this.state.state,
remindMembers: this.state.remindMembers,
type: type === 'notice' ? 1 : 0
})
}
await保证了单个请求回来才会执行下一条请求
当然 用户选择图片或视频时 先展示本地的 等到需要发布时 先把图传到七牛 获得url 再调用后台接口
这里有个问题就是 调用后台接口失败了 但你的imageUrls已经存过一组七牛数据了 这样就会导致再调后台成功的话 就多出一组图片数据
解决就是 失败了 清空imageUrls即可
网友评论