max*_*ver 6 firebase react-native firebase-storage
我的组件状态有两个图像路径
我尝试上传一个函数内的一个图像,但得到一个错误:
Firebase Storage: Invalid argument in 'put' at index 0: Expected Blob or file
Run Code Online (Sandbox Code Playgroud)
和我的功能
submitImages = () => {
// Upload images to Firebase storage
let user = firebaseAuth.currentUser;
let imagesRef = storageRef.child('productImages/' + user.uid);
imagesRef.put(this.state.imageFront).then(snapshot => {
console.log('Uploaded ' + this.state.imageFront);
});
}
Run Code Online (Sandbox Code Playgroud)
我应该做些什么来将这些图像传输到Firebase.谢谢!
Fra*_*Jr. 10
错误说的是你需要使用blob.您可以使用react-native-fetch-blob:https://github.com/wkh237/react-native-fetch-blob
看看这个例子:https://github.com/dailydrip/react-native-firebase-storage/blob/master/src/App.js#L43-L69
我发布了我的代码,因为这对我来说有点令人沮丧:
要将图像上传到firebase.storage,您需要将图像上传为Blob.如果您不知道Blob是什么,请不要担心:BLOB代表B inary L arge OB ject.
步骤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;
Run Code Online (Sandbox Code Playgroud)
第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)
})
})
}
Run Code Online (Sandbox Code Playgroud)
那你怎么称呼这个功能呢?传递图像的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.
})
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用react-native-firebase上传图像以存储https://rnfirebase.io/
const storage = firebase.storage();
const sessionId = new Date().getTime();
const imageRef = storage.ref('images').child(`${sessionId}`);
return imageRef.putFile(uri);
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是我发现使用React Native将文件/图像上传到Firebase存储的最佳方法。除Expo SDK外,此方法不使用任何第三方库。
获取要上传的图像的文件URI。为此,我们将需要使用Expo ImagePicker。包含此代码块的最佳位置是带有onPress处理程序的按钮。
ImagePicker.launchImageLibraryAsync({
mediaTypes: "Images"
}).then((result)=>{
if (!result.cancelled) {
// User picked an image
const {height, width, type, uri} = result;
return uriToBlob(uri); // will follow later
}
})
Run Code Online (Sandbox Code Playgroud)从图像URI生成BLOB。有很多第三方库可以帮助您做到这一点。但是,如果您不想安装库,则可以使用XMLHttpRequest。React Native文档建议我们使用Fetch API,但现在我们不能使用它,因为它会引发一个错误,我们只能获取https://url,而我们的URI是一个file://。有一种方法可以通过,但是使用XMLHttpRequest将使事情变得简单得多。
uriToBlob = (uri) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
// return the blob
resolve(xhr.response);
};
xhr.onerror = function() {
// something went wrong
reject(new Error('uriToBlob failed'));
};
// this helps us get a blob
xhr.responseType = 'blob';
xhr.open('GET', uri, true);
xhr.send(null);
});
}
Run Code Online (Sandbox Code Playgroud)我们有BLOB,让我们将其上传到Firebase。如Firebase Docs中所述,这部分非常简单。
uploadToFirebase = (blob) => {
return new Promise((resolve, reject)=>{
var storageRef = firebase.storage().ref();
storageRef.child('uploads/photo.jpg').put(blob, {
contentType: 'image/jpeg'
}).then((snapshot)=>{
blob.close(); // let's free up the blob
resolve(snapshot);
}).catch((error)=>{
reject(error);
});
});
}
Run Code Online (Sandbox Code Playgroud)就是这样,您现在可以将文件上传到Firebase Storage。关键的部分是获取文件URI并将其转换为BLOB。您可以在此处阅读有关此方法的更多信息。
| 归档时间: |
|
| 查看次数: |
18708 次 |
| 最近记录: |