gpt4 book ai didi

javascript - 无法将图片上传到 Firebase

转载 作者:行者123 更新时间:2023-11-28 03:49:44 26 4
gpt4 key购买 nike

问题

我正在尝试使用 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 图像裁剪选择器,以便 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>

关于javascript - 无法将图片上传到 Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48107019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com