我发布我的代码,因为这对我来说有点令人沮丧:
要将图像上传到 firebase.storage,您需要将图像作为 Blob 上传。如果您不知道 Blob 是什么,请不要担心:BLOB 代表 Binary Large OB喷射。
第 1 步。
npm install --save react-native-fetch-blob
第 2 步。
// copy and paste this code where you will handle the file upload
import RNFetchBlob from 'react-native-fetch-blob'
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
第 3 步。
// The uploadImage function that you are going to use:
function uploadImage(uri, mime = 'image/jpeg', name) {
return new Promise((resolve, reject) => {
let imgUri = uri; let uploadBlob = null;
const uploadUri = Platform.OS === 'ios' ? imgUri.replace('file://', '') : imgUri;
const { currentUser } = firebase.auth();
const imageRef = firebase.storage().ref(`/jobs/${currentUser.uid}`)
fs.readFile(uploadUri, 'base64')
.then(data => {
return Blob.build(data, { type: `${mime};BASE64` });
})
.then(blob => {
uploadBlob = blob;
return imageRef.put(blob, { contentType: mime, name: name });
})
.then(() => {
uploadBlob.close()
return imageRef.getDownloadURL();
})
.then(url => {
resolve(url);
})
.catch(error => {
reject(error)
})
})
}
那么你如何调用这个函数呢?
将图像的 URI 作为第一个参数传递。在我的情况下,img1, img2, img3 指向图像 URI 的变量,我想上传在我的手机上。它们看起来像 '/Phone/Pics/imageToUpload.jpeg' 等。
作为第二个参数,您可以传递'image/jpeg',最后一个参数是您要为图像指定的名称。选择你喜欢的名字。
但是,如果我有几张图片并且想要上传它们并且想要正确处理上传怎么办。如果一个上传成功而另一个没有上传怎么办?
然后这样做:
let imgPromises = [];
imgPromises.push(uploadImage(img1, 'image/jpeg', 'imageOne'));
imgPromises.push(uploadImage(img2, 'image/jpeg', 'imageTwo'));
imgPromises.push(uploadImage(img3, 'image/jpeg', 'imageOne'));
Promise.all(imgPromises).then(urls => {
// ALL IMAGES SUCCEEDED and you will get an array of URIS that you can save to your database for later use!
}).catch(error => {
// One OR many images failed the upload. Give feedback to someone.
})