对于我的react-native (我正在使用世博会)应用程序,我希望用户上传一张头像,并将其存储在firebase存储中。为此,我使用了this example code,并为我的应用程序修改了它。但是,这个示例对我不起作用,除非我处于调试模式。
我可以打开ImagePicker然后编辑照片,但上传失败。
我发布了代码的快照。单击按钮即可调用_pickImage()。
此问题的原因可能是什么?我的建议是,在调试模式下,应用程序有更多的时间来处理函数,因为在调试模式下,应用程序真的很慢。
我对react-native (以及一般的应用程序开发)非常陌生,我对此表示歉意!
非常感谢。
_pickImage = async () => {
let pickerResult = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
this._handleImagePicked(pickerResult);
};
_handleImagePicked = async pickerResult => {
try {
this.setState({ uploading: true });
if (!pickerResult.cancelled) {
uploadUrl = await uploadImageAsync(pickerResult.uri);
this.setState({ image: uploadUrl });
}
} catch (e) {
console.log(e);
alert('Upload failed, sorry :(');
} finally {
this.setState({ uploading: false });
}
};
}
async function uploadImageAsync(uri) {
// Why are we using XMLHttpRequest? See:
// https://github.com/expo/expo/issues/2402#issuecomment-443726662
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);
});
const ref = firebase
.storage()
.ref()
.child(uuid.v4());
const snapshot = await ref.put(blob);
// We're done with the blob, close and release it
blob.close();
return await snapshot.ref.getDownloadURL();
}发布于 2019-01-29 14:50:25
我的更新代码
import { ImagePicker } from 'expo';
import { RNS3 } from 'react-native-aws3';
YellowBox.ignoreWarnings(['Setting a timer']);
var _ = require('lodash');
.
.
.
componentDidMount(){
this.firebaseRef = firebase.database().ref('newsfeed')
this.firebaseRef.on('value', snap => {
const newsfeed = snap.val()
const newNewsfeed = _.reverse(_.values(newsfeed));
this.setState({ postList: newNewsfeed, loadingPost: false })
})
}
async onAddPhoto(){
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
aspect: [4, 3],
});
if (!result.cancelled) {
this.setState({ photo: result.uri });
options["contentType"] = result.type
}
}
onPressPost(){
this.setState({ loading: true})
const _this = this
let post = {}
post["id"] = firebase.database.ServerValue.TIMESTAMP
post["text"] = this.state.text
if(this.state.photo){
const uri = this.state.photo
const ext = uri.substr(uri.lastIndexOf('.') + 1);
const name = Math.round(+new Date()/1000);
let file = {
name: name+"."+ext,
type: "image/"+ext,
uri
}
RNS3.put(file, options).then(response => {
if(response.status === 201){
post["photo"] = response.body.postResponse.location
firebase.database().ref('newsfeed').push(post)
_this.setState({ text: '', photo: null, loading: false})
}
});
}else {
firebase.database().ref('newsfeed').push(post)
_this.setState({ text: '', photo: null, loading: false})
}
}https://stackoverflow.com/questions/54407956
复制相似问题