我在查看上传到Firebase的图像文件时遇到了麻烦,只是注意到问题出在firebase中。
firebase存储控制台中有两个文件。一个从我的IOS模拟器(八位字节流)和其它直接上传到从浏览器,其上载正确并是可见的控制台上载。
这是我的选择和上传功能:
_selectPhoto = async () => {
const status = await getPermission(Permissions.CAMERA_ROLL);
if (status) {
let imageName = "pic"
const result = await ImagePicker.launchImageLibraryAsync(options);
if (!result.cancelled) {
Animated.timing(this.animatedWidth, {
toValue: 600,
duration: 15000
}).start()
this.uploadImage(result.uri, imageName)
.then(() => {
this.props.navigation.navigate('Profile')
})
.catch((error) => {
Alert.alert('Must Sign In');
this.props.navigation.navigate('Login')
console.log(error);
})
}
}
};
uploadImage = async (uri, imageName) => {
const user = firebase.auth().currentUser;
const response = await fetch(uri);
const blob = await response.blob();
let storageRef = firebase.storage().ref().child(''images/'+user.displayName+'/'+imageName+'.jpg'');
const snapshot = await storageRef.put(blob);
blob.close();
snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log("File available at", downloadURL);
user.updateProfile({
photoURL: downloadURL.toString(),
}).then(function() {
console.log('saved photo')
}).catch(function(error) {
console.log('failed photo')
});
});
}
当我在控制台中获得链接时,它也包含媒体和令牌:
... .appspot.com / o / profile-pic.jpg?alt = media&token = 56eb9c36-b5cd-4dbb-bec1-3ea5c3a74bdd
如果我CMD +单击VS Code,则会收到错误消息:
{
error: {
code: 400,
message: "Invalid HTTP method/URL pair."
}
}
于是很自然,当我把该链接的浏览器,它会下载具有该名称的文件,但是他说:
无法打开文件“ pic.jpg”。 它可能已损坏或使用 文件格式预览不能识别。
也许这可能是一些与mediaTypes,但我不完全知道如何使用它。
mediaTypes:字符串 - 选择什么样的媒体类型来挑选。用法: ImagePicker.MediaTypeOptions,这里是一个:图像, 画,所有
谢谢!
答案 0 :(得分:3)
过去几天,我一直在同一个问题上作斗争。通过遵循Firebase Upload example in the Expo repo,我终于能够按预期方式上传和渲染图像。我不完全了解为什么它起作用,但似乎Firebase不喜欢由
生成的blob。 const blob = await response.blob();
尝试将以上内容替换为:
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(xhr.response);
};
xhr.onerror = function(e) {
console.log(e);
reject(new TypeError('Network request failed'));
};
xhr.responseType = 'blob';
xhr.open('GET', uri, true);
xhr.send(null);
});