Home > front end >  I'm trying to upload an image to firebase storage and get the download url
I'm trying to upload an image to firebase storage and get the download url

Time:08-19

Newbie here, I'm trying to upload an image to firebase storage and then get the download url. Then I'll add that url as data to save on firestore. I'm able to upload successfully and get the image reference but the problem is with getDownloadURL(). I'm having trouble formatting the promise. I've tried multiple ways but can't seem to figure it out.

TypeError: ref._throwIfRoot is not a function
    at getDownloadURL$1 (index.esm2017.js?f61e:2956:1)
    at getDownloadURL (index.esm2017.js?f61e:3412:1)
    at eval (cloudStorageFunctions.js?05e1:17:34)
const productImagesRef = ref(storage, 'images/product-images');

function getImageURL(fileName, file) {
    const filePath = `${productImagesRef}/${fileName}`;
    const imageRef = ref(storage, filePath);

    return uploadBytes(imageRef, file)
        .then(snapshot => {
            console.log(`File: ${fileName} uploaded successfully.`);
            return snapshot.metadata.fullPath;      
        })
        .then(path => {
            console.log(typeof path, path);
            return getDownloadURL(path);
        })
        .then(src => {
            console.log(src);
            return src;
        })
        .catch(e => {
            console.error(e);
        })
}

The data is submitted via a form:

async function handleSubmit() {
        let src = await getImageURL(imageName, imageFile);

        setImageSrc(src);

        const data = {
            id: id,
            imageSrc: imageSrc,
            description: description,
            category: category,
            discount: discount,
            discountPrice: discountPrice,
            price: price,
            sizes: sizes,
            totalQuantity: quantity,
            type: type,
        }

        console.log(data);

        if(imageSrc) await addProducts(data);
        
        setImageFile('');
        setImageName('');
        setImageSrc('');
        setDescription('');
        setCategory('');
        setDiscount(false);
        setDiscountPrice(0);
        setPrice('');
        setSizes([]);
        setQuantity('');
        setType([]);
        setDisplay('none')

        alert('Added');
    }

CodePudding user response:

The uploadBytes function returns a Promise<UploadResult>. You're passing that result to the getDownloadURL function, but that expects a StorageReference.

Simple fix:

return uploadBytes(imageRef, file)
    .then(snapshot => {
        return snapshot.metadata.fullPath;      
    })
    .then(path => {
        return getDownloadURL(imageRef);
    })

CodePudding user response:

getDownloadURL takes a storage reference just like the one you passed to uplaodBytes.

return getDownloadURL(imagePath);

It's not clear to me what you are currently passing instead. I suggest reviewing the documentation for an example.

  • Related