[英]Firebase Storage - Upload Image with React Native, Error loading Preview
This is the code which I use to upload images to firebase storage这是我用来将图像上传到 firebase 存储的代码
const filename = image.substring(image.lastIndexOf('/') + 1);
const uploadUri = Platform.OS === 'ios' ? image.replace('file://', '') : image
var metadata = {
contentType: 'image/jpeg',
};
const task = firebase.storage().ref().put(uploadUri, metadata)
try {
await task
} catch(err) {
console.log(err)
}
But when I check the firebase console it shows, error loading preview, and the file size is 9B for a image.但是当我检查 firebase 控制台时,它显示错误加载预览,并且图像的文件大小为 9B。 Is there something Im missing.
有什么我想念的吗。
Im using Expo managed, expo-image-picker to select images.我使用 Expo 管理的、expo-image-picker 到 select 图像。
Change it to this改成这个
const filename = image.substring(image.lastIndexOf('/') + 1);
const uploadUri = Platform.OS === 'ios' ? image.replace('file://', '') : image
let formData = new FormData();
formData.append("image", {
name: filename,
type: 'image/jpeg',
uri: uploadUri
})
var metadata = {
contentType: 'image/jpeg',
};
const task = firebase.storage().ref().put(formData, metadata)
try {
await task
} catch(err) {
console.log(err)
}
I found a way, I had to create a blob and then upload the blob to firebase我找到了一种方法,我必须创建一个 blob,然后将 blob 上传到 firebase
const filename = image.substring(image.lastIndexOf('/') + 1);
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(xhr.response);
};
xhr.onerror = function() {
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", image, true);
xhr.send(null);
});
const ref = firebase
.storage()
.ref()
.child(filename);
const task = ref.put(blob, { contentType: 'image/jpeg' });
task.on('state_changed',
(snapshot) => {
console.log(snapshot.totalBytes)
},
(err) => {
console.log(err)
},
() => {
task.snapshot.ref.getDownloadURL().then((downloadURL) => {
console.log(downloadURL);
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.