上传文件 Firebase - 高效

问题描述 投票:0回答:1

我正在使用此代码将文件上传到 Firebase Storage,但此代码看起来很笨重并且运行缓慢。如何提高文件存储到 Firebase 的速度?

const uploadToStorage = async (uri: string, path: string, category: string, subcategory: string): Promise<string> => {
    try {
        const filename = `${Date.now()}-${Math.random().toString(36).substring(7)}.jpg`; // Unique filename
        const storageRef = ref(storage, `/${category}/${subcategory}/${filename}`);

        const response = await fetch(uri);
        const blob = await response.blob();

        const uploadTask = uploadBytesResumable(storageRef, blob);

        return new Promise<string>((resolve, reject) => {
            uploadTask.on('state_changed',
                (snapshot) => {
                    // Optional: Update progress to the user
                    const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                    console.log(`Upload is ${progress}% done`);
                },
                reject, // Handle unsuccessful uploads
                async () => {
                    try {
                        const downloadURL = await getDownloadURL(uploadTask.snapshot.ref);
                        resolve(downloadURL); // Resolve with the download URL
                    } catch (error) {
                        console.error(`Error getting download URL:`, error);
                        reject(error);
                    }
                }
            );
        });
    } catch (error) {
        console.error("Error during the upload process", error);
        throw error;
    }
};

如果我尝试这样的操作,它会在第二次或第三次时使我的应用程序崩溃。我需要一些可靠的东西,每次都可以工作,但也能以不错的速度移动。

const uploadToStorage = async (uri: string, path: string, category: string, subcategory: string): Promise<string> => {
    try {
        const filename = `${Date.now()}-${Math.random().toString(36).substring(7)}.jpg`; // Unique filename
        const storageRef = ref(storage, `/${category}/${subcategory}/${filename}`);

        const response = await fetch(uri);
        const blob = await response.blob();

        const uploadTask = uploadBytes(storageRef, blob);

        return new Promise<string>((resolve, reject) => {
            uploadTask.then(
                async (snapshot) => {
                    const downloadURL = await getDownloadURL(snapshot.ref);
                    resolve(downloadURL);
                },
            ).catch((error) => {
                console.error("Error uploading image", error);
                reject(error);
            });
        });
    } catch (error) {
        console.error("Error during the upload process", error);
        throw error;
    }
};
reactjs typescript firebase react-native firebase-storage
1个回答
0
投票

这对我有用:

    async function processUploadImage(uri, fileName, docId) {
        const response = await fetch(uri);
        const blob = await response.blob();
        const storageRef = ref(storage, `${id}/evidence${docId}/${fileName}`);
        const uploadTask = uploadBytesResumable(storageRef, blob);

        uploadTask.on(
            "state_changed",
            (snapshot) => {
                const progress =
                    (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
                console.log("Loading..." + progress.toFixed() + "%");
            },
            (error) => {
                console.log("Error: ", error.serverResponse);
                setIsLoading(false);
                setCodeStorage("");
                setImage([]);
                setUrlData([]);
            },
            () => {
                getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURL) => {
                    setUrlData((prevFiles) => [...prevFiles, { uri: downloadURL }]);
                });
            }
        );
    }

我正在使用 expo imagepicker,在配置它时我选择了中等图像质量,因此即使有多个图像,上传速度也会更快:

let result = await ImagePicker.launchImageLibraryAsync({
                mediaTypes: ImagePicker.MediaTypeOptions.Images,
                allowsMultipleSelection: true,
                aspect: [4, 3],
                quality: 0.5,
                orderedSelection: true,
                selectionLimit: 20,
            });
© www.soinside.com 2019 - 2024. All rights reserved.