[英]Uploading images to Firebase doesn't work
我正在嘗試使用 React Native 將圖像上傳到 Firebase。 我正在使用此代碼來執行此操作,當我使用此代碼時,什么也沒有發生。 進度百分比永遠不會上升*。
var uploadTask =
storageRef.child('images/'+expoID+this.state.time).put(
this.state.image, metadata
);
this.state.time
是時間戳,它是在屏幕開始時定義的狀態,因此圖像和帖子沒有不同的時間戳。
this.state.image
是用戶手機上圖像的直接路徑。
元數據是:
{
contentType: 'image/jpeg'
};
我認為問題可能是this.state.image
變量是用戶手機上文件的路徑,這可能是錯誤的格式。 問題是我不知道還有什么可以放在那里。
*進度百分比代碼:
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
function(snapshot) {
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
this.setState({progress:'Upload is ' + progress + '% done'});
});
}
我必須使用 react native fetch blob 和 react native imagecrop picker for Firebase 才能接收我的圖像。 這是我所做的:
openImage() {
this.setState({ loading: true });
const imageChangeFail = () => {
this.setState({ loading: false });
};
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
const item = Date.now() + Math.random();
ImagePicker.openPicker({
width: 400,
height: 300,
cropping: true,
mediaType: 'photo',
})
.catch(imageChangeFail())
.then(image => {
const imagePath = image.path;
const uploadBlob = null;
const storage = firebase.storage();
const storageRef = storage.ref();
const imageRef = storageRef.child(item + '.jpg');
const mime = 'image/jpg';
fs.readFile(imagePath, '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) => {
const { image } = this.props;
//this.props.entryUpdate is my action creator
//to update a piece of state called
//entryForm. Image is just one piece of that
//state.
this.props.entryUpdate({ prop: 'image', value:
url })
})
this.setState({ loading: false });
});
}
然后我會在這里調用 openImage() :
<TouchableOpacity
onPress={() => this.openImage()}
>
<Text
style={{
color: '#000',
alignSelf: 'center',
}}
>
<Icon name="photo-camera" size={45} color="#000" />
</Text>
</TouchableOpacity>
嘗試:
uploadImage = async (expoID) => {
var response = wait fetch(this.state.image);
var blob = await response.blob();
storageRef.child('images/'+expoID+this.state.time).put(blob)
.then( console.log('sucess') )
.catch( (error) => console.log(error.messaeg) )
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.