Добрый день всем! У меня есть ошибка в моем проекте. Не могли бы вы взглянуть на это и сказать, что не так с моим кодом? дело в том, что я работал с загрузкой изображений в Firebase Store, и я хочу сохранить его URL с другими данными в облачном хранилище Firefox. Он отлично работает, когда я загружаю фотографию только в хранилище Firebase, но когда я применяю код для вставки в облако. FireStore это не сохранить в хранилище, но вставка для FireStore работает нормально. пожалуйста, помогите мне с этим. Я был бы очень признателен вам.
Я попытался записать в лог путь процесса, и он показывает это =>
и вот мой полный код
import React, { Component } from 'react';
import {
StyleSheet, View, Alert, TextInput, Button, Text, Platform, TouchableOpacity, ListView,Dimensions, ActivityIndicator, Image, ScrollView, KeyboardAvoidingView, Picker
} from 'react-native';
import { Actions } from 'react-native-router-flux'; // New code
import firebase from './firebase';
import RNFetchBlob from 'react-native-fetch-blob'
import ImagePicker from 'react-native-image-picker'
// More info on all the options is below in the README...just some common use cases shown here
var options = {
title: 'Select Avatar',
storageOptions: {
skipBackup: true,
path: 'images'
}
};
const tempWindowXMLHttpRequest = window.XMLHttpRequest;
// Prepare Blob support
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.Blob = Blob;
const originalBlob = window.Blob;
window.XMLHttpRequest = tempWindowXMLHttpRequest;
export default class GoldScreen extends Component{
constructor(props) {
super(props);
this.ref = firebase.firestore();
this.getImage = this.getImage.bind(this)
this.state = {
image_uri: 'https://avatars0.githubusercontent.com/u/12028011?v=3&s=200',
image: '',
section: '',
unit: '',
price: '',
product: '',
status: '',
hasError: false,
errorText: '',
isLoading: false,
};
}
uploadImage(uri, mime = 'application/octet-stream') {
return new Promise((resolve, reject) => {
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
let uploadBlob = null
const imageRef = firebase.storage().ref('images').child('bsavdbavdghasfdahsgdfahdgv dhgasdgasdghasd')
fs.readFile(uploadUri, '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) => {
resolve(url)
})
.catch((error) => {
reject(error)
})
})
}
getImage(){
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
// let source = { uri: response.uri };
// this.setState({image_uri: response.uri})
// You can also display the image using data:
// let image_uri = { uri: 'data:image/jpeg;base64,' + response.data };
this.uploadImage(response.uri)
.then(url => { alert('uploaded'); this.setState({image_uri: url}) })
.catch(error => console.log(error))
}
});
console.log(this.state.image_uri)
console.ignoredYellowBox = ['Setting a timer'];
}
updateUser = (TextInputValue) => {
this.setState({ status: TextInputValue })
}
render(){
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<ScrollView
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}>
<KeyboardAvoidingView enabled >
<Image
style={{width: 100, height: 100}}
source={{uri: this.state.image_uri}}
/>
<Button
onPress={this.getImage}
title="Change Image"
color="#841584"
/>
<TextInput
placeholder="Enter Product"
onChangeText={ TextInputValue => this.setState({ product : TextInputValue }) }
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter Price"
keyboardType={'decimal-pad'}
onChangeText={ TextInputValue => this.setState({ price : TextInputValue }) }
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<Picker
selectedValue={this.state.unit}
style={{height: 50, width: 300}}
onValueChange={(TextInputValue, itemIndex) =>
this.setState({unit: TextInputValue})}>
<Picker.Item label = "Select Unit" />
<Picker.Item label = "Kilo" value = "Kilo" />
<Picker.Item label = "Each" value = "Each" />
<Picker.Item label = "Bottle" value = "Bottle" />
<Picker.Item label = "Pack" value = "Pack" />
<Picker.Item label = "Sack" value = "Sack" />
</Picker>
<Picker
selectedValue={this.state.section}
style={{height: 50, width: 300}}
onValueChange={(TextInputValue, itemIndex) =>
this.setState({section: TextInputValue})}>
<Picker.Item label = "Select Section" />
<Picker.Item label = "Meat" value = "Meat" />
<Picker.Item label = "Vegetable" value = "Vegetable" />
<Picker.Item label = "Fruits" value = "Fruits" />
<Picker.Item label = "Biscuits" value = "Biscuits" />
<Picker.Item label = "Condiments" value = "Condiments" />
<Picker.Item label = "Canned Goods" value = "Canned Goods" />
<Picker.Item label = "Drinks" value = "Drinks" />
<Picker.Item label = "Diapers/Napkin" value = "Diapers/Napkin" />
<Picker.Item label = "Frozen Products" value = "Frozen Products" />
<Picker.Item label = "Junk Foods" value = "Junk Foods" />
<Picker.Item label = "Milk" value = "Milk" />
<Picker.Item label = "Soap/Shampoo" value = "Soap/Shampoo" />
<Picker.Item label = "Pesonal Items" value = "Pesonal Items" />
<Picker.Item label = "Pasta/Noodleslete" value = "Pasta/Noodles" />
</Picker>
<TextInput
placeholder="Enter Description"
multiline={true}
numberOfLines={4}
onChangeText={ TextInputValue => this.setState({ description : TextInputValue }) }
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter image"
onChangeText={ TextInputValue => this.setState({ image_uri : TextInputValue }) }
value={ this.state.image_uri }
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={() => this.saveUserdata()} >
<Text style={styles.TextStyle}> INSERT PRODUCT TO SERVER </Text>
</TouchableOpacity>
<TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={() => Actions.black()} >
<Text style={styles.TextStyle}> SHOW ALL INSERTED PRODUCTS RECORDS</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</ScrollView>
</View>
);
}
signup() {
if(this.state.product===""||this.state.price===""||this.state.unit===""||this.state.section==="") {
this.setState({hasError: true, errorText: 'Please fill all fields !'});
return;
}
this.saveUserdata();
}
saveUserdata() {
const newDocumentData = this.ref.collection('products').doc().id;
this.setState({
loading: true,
});
const userId = firebase.auth().currentUser.uid;
this.ref.collection('products').doc(newDocumentData).set({
store_id: firebase.auth().currentUser.uid,
pr_name: this.state.product,
pr_id: newDocumentData,
pr_price: this.state.price,
pr_unit: this.state.unit,
pr_store_name: firebase.auth().currentUser.email, //change into name of store.
pr_section : this.state.section,
pr_image: this .state.image_uri,
prod_status: 'active',
}).then((docRef) => {
this.setState({
image: '',
section: '',
unit: '',
price: '',
product: '',
status: '',
isloading: false,
});
Actions.gold();
})
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ffdf00',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: '#ffffff',
},
MainContainer :{
alignItems: 'center',
flex:1,
paddingTop: 30,
backgroundColor: '#fff'
},
MainContainer_For_Show_StudentList_Activity :{
flex:1,
paddingTop: (Platform.OS == 'ios') ? 20 : 0,
marginLeft: 5,
marginRight: 5
},
TextInputStyleClass: {
textAlign: 'center',
width: '90%',
marginBottom: 7,
height: 40,
borderWidth: 1,
borderColor: '#FF5722',
borderRadius: 5 ,
},
TouchableOpacityStyle: {
paddingTop:10,
paddingBottom:10,
borderRadius:5,
marginBottom:7,
width: '90%',
backgroundColor: '#00BCD4'
},
TextStyle:{
color:'#fff',
textAlign:'center',
},
rowViewContainer: {
fontSize: 20,
paddingRight: 10,
paddingTop: 10,
paddingBottom: 10,
},
imageContainer: {
backgroundColor: '#fe5b29',
height: Dimensions.get('window').height
},
backgroundImage: {
flex: 1,
resizeMode: 'cover',
},
uploadContainer: {
backgroundColor: '#f6f5f8',
borderTopLeftRadius: 45,
borderTopRightRadius: 45,
position: 'absolute',
bottom: 0,
width: Dimensions.get('window').width,
height: 200,
},
uploadContainerTitle: {
alignSelf: 'center',
fontSize: 25,
margin: 20,
fontFamily: 'Roboto'
},
uploadButton: {
borderRadius: 16,
alignSelf: 'center',
shadowColor: "#000",
shadowOffset: {
width: 7,
height: 5,
},
shadowOpacity: 1.58,
shadowRadius: 9,
elevation: 4,
margin: 10,
padding: 10,
backgroundColor: '#fe5b29',
width: Dimensions.get('window').width - 60,
alignItems: 'center'
},
uploadButtonText: {
color: '#f6f5f8',
fontSize: 20,
fontFamily: 'Roboto'
}
});
и вот мои правила для моего хранилища пожарной базы
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}