我有多个存储在数组中的图像(存储在数组中的图像路径)。然后我使用for循环上传每个图像,但只上传最后一个图像。我使用react native fetch blob和firebase
for(var i = 0; i < this.state.imagesUri;i++){
Blob.build(RNFetchBlob.wrap(this.state.imagesUri[i].path),{ type : 'image/jpeg' })
.then((blob) => firebase.storage()
.ref("userPhoto").child("image"+i)
.put(blob, { contentType : 'image/png' }).then(()=>{
var storage = firebase.storage().ref("userPhoto/").child("image"+i);
storage.getDownloadURL().then((url)=>{
var url = url;
});
})
);
}
我希望这个能帮上忙
onSend(images) {
let photo = images.map( img=> img.image);
photo.forEach((image, i) => {
const sessionId = new Date().getTime();
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest =
RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
let uploadBlob = null;
let mime = 'image/jpg';
const imageRef = this.image.child(`${sessionId}${i}`);
fs.readFile(image, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob;
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close();
return imageRef.getDownloadURL()
})
.then((url) => {
console.log(url)
})
.catch((error) => {
});
})
}
好的,首先,你需要缓存数组this.state.imagesUri
的长度。
这将使你的for循环看起来像for(var i = 0, length = this.state.imagesUri.length; i < length;i++){
,我希望你注意到你不再检查i < this.state.imagesUri
(这是不正确的,因为imagesUri
是一个数组)。