我正在尝试将多个图像上传到Firebase,看来确实可行。
代码的工作方式是通过遍历一系列本地图像路径。然后将每个图像上传到Firebase并提供URL。然后,我将这些URL存储到一个数组中,并用它替换原来的内容(本地图像路径)。
但是问题出在哪里,我发现这有时可行,有时我得到undefined
作为图像src="..."
。即:
<b>Hello World</b><img src=\"https://firebasestorage.googleapis.com/xxxx>Another image <img src=\"undefined">`
我还要指出,所有图像的确上传到Firebase存储中。因此,不确定导致以下问题的以下代码有什么问题。任何帮助表示赞赏。谢谢。
///// MULTI IMAGE UPLOAD WITH TEXT
export const postStorymulti = (desc, imageArray) => {
return (dispatch) => {
dispatch({
type: POST_STORY
});
this.multiuploadImage(imageArray).then(url =>
this.changedesc(desc, imageArray).then(uploadDescription =>
firebase.database().ref('blogs/' + currentUser.uid).push({
blogDescription: uploadDescription,
})
).catch(error => postStoryFail(dispatch, error))
).catch(error => postStoryFail(dispatch, error));
};
};
在这里,我将每个本地图像上传到Firebase,并将这些URL存储到名为imageArray
的新数组中:
multiuploadImage = (imageArray) => {
return new Promise((resolve, reject) => {
for (var i = 0; i < imageArray.length; i++) {
let ii = i;
const uploadUri = imageArray[i];
let uploadBlob = null;
let mime = 'image/jpg';
const imageRef = firebase.storage().ref('uploads').child(uiqueID());
fs.readFile(uploadUri, '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) => {
resolve(url)
//URLS stored here
newimageArray[ii] = url;
})
.catch((error) => {
reject(error)
});
}
});
}
在这里,我将原来的img src="..."
替换为Firebase URL:
changedesc = (desc, imageArray) => {
return new Promise((resolve, reject) => {
var uploadDescription;
var rgx = /<img src="([^">]+)"/g;
var match;
for (var ya = 0; ya < imageArray.length; ya++) {
match = rgx.exec(nn);
uploadDescription = desc.replace(match[1], newimageArray[ya]);
}
resolve(uploadDescription)
.catch((error) => {
reject(error)
});
});
}