Image picker issue (Firebase & MongoDB)

37 Views Asked by At

I tried to upload the image to firebase by use image picker (JS) it stated Network Error hence, I found out there are error by using fetch.

if (!result.cancelled) {
    const source = { uri: result.uri };
    setImage(source);

    const response = await fetch(result.uri);
    const blob = await response.blob();
    const filename = result.uri.substring(result.uri);

    const ref = firebase.storage().ref().child(filename);
    const snapshot = await ref.put(blob);
    const url = await snapshot.ref.getDownloadURL();

    // console.log(url)
    return url
}
else {
    return null
}

I've amended to

const handleUpload = async () => {
        setUploading(true);

try {
    const { uri } = await FileSystem.getInfoAsync(image);
    const blob = await new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.onload = () => {
            resolve(xhr.response);
        };
        xhr.onerror = (e) => {
            reject(new TypeError('Network request failed'));
        };
        xhr.responseType = 'blob';
        xhr.open('GET', uri, true);
        xhr.send(null);
    });

however how could I input mongoDB

const handleUpload = () => {
    // pickImage()
    AsyncStorage.getItem('user')
        .then(data => {
            setLoading(true)

            pickImage().then(url => {
                fetch('http://10.0.7.1:3000/setprofile_pic', {
                    method: 'post',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        email: JSON.parse(data).user.email,
                        profile_pic: url
                    })
                })
                    .then(res => res.json()).then(
                        data => {
                            if (data.message === "Profile picture updated successfully") {
                                setLoading(false)
                                alert('Profile picture updated successfully')
                                navigation.navigate('Settings_1')
                            }
                            else if (data.error === "Invalid Credentials") {
                                alert('Invalid Credentials')
                                setLoading(false)
                                navigation.navigate('Login')
                            }
                            else {
                                setLoading(false)
                                alert("Please Try Again");
                            }
                        }
                    )
                    .catch(err => {
                        console.log(err)
                    })

            })
        })
}      

How can I save the profile picture from Firebase and input it into mongoDB?

0

There are 0 best solutions below