【问题标题】:Uploading file from react to firebase fails从反应上传文件到firebase失败
【发布时间】:2020-10-07 00:39:39
【问题描述】:

我正在尝试将文件从我的 react 网站上传到 firebase 存储。文件存储在 firebase 但格式不正确(pdf),我也无法打开文件。当我从邮递员上传文件时,它可以工作。

我上传文件的代码:

onUploadFile = (event, authUser) => {
    const {files} = this.state;

    let reader = new FileReader();

    reader.readAsDataURL(files[0]);
    reader.onload = async (e) => {
        const url = "https://us-central1-xxxxxx-4853a.cloudfunctions.net/uploadFileFirebase";
        const fileNameResult = await fetch(e.target.result).then(res => res.blob());
        const data = new FormData();
        data.append(files[0].name, fileNameResult);
        return axios.post(url, data, {
            headers: {
                "Content-Type": "multipart/form-data"
            }
        })
        .then(response => console.log('result', response));
    };

    event.preventDefault();
};

在节点js中我写了:

exports.uploadFileFirebase = functions.https.onRequest((req, res) => {
    cors(req, res, () => {

        if (req.method !== "POST") {
            return res.status(500).json({
                message: "Not allowed"
            });
        }

        const busboy = new Busboy({headers: req.headers});

        console.log(busboy);

        let uploadData = null;
        let fileName = null;
        busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
            console.log('in file');
            try {
                console.log('filename ==>');
                console.log(filename);
                fileName = filename;
                const filepath = path.join(os.tmpdir(), filename);
                uploadData = {file: filepath, type: mimetype};

                file.pipe(fs.createWriteStream(filepath));
            } catch (e) {
                console.log(e);
            }
        });

        busboy.on("finish", () => {
            const bucket = gcs.bucket("xxxxxxx-4853a.appspot.com"); //TODO make map with company reference
            bucket.upload(uploadData.file, {
                uploadType: "media",
                metadata: {
                    metadata: {
                        contentType: uploadData.type
                    }
                }
            })
            .then(() => {
                return res.status(200).json({
                    message: 'file uploaded'
                });
            })
            .catch(err => {
                return res.status(500).json({
                    error: err.toString()
                });
            });
        });
        busboy.end(req.rawBody);
    });
});

文件以名称“blob”保存在存储中。并有以下数据:

[![在此处输入图片描述][1]][1]

我还从文件中进行数据提取,数据被正确提取。如何使用正确的文件名和 pdf 类型正确保存文件,以便我可以在 firebase 中打开文件。

有什么想法吗?

在 firebase 中打开文件的解决方案是将 uuid 添加到元数据中。

metadata: {
                    metadata: {
                        contentType: uploadData.type,
                        firebaseStorageDownloadTokens: '1f040c40-6000-48c6-8320-4fa41d9b1730 '
                    }
                }

【问题讨论】:

    标签: node.js reactjs firebase file


    【解决方案1】:

    formdata.append 有第三个文件名参数:

    
    data.append(files[0].name, fileNameResult, files[0].name);
    

    将 name 属性添加到 blob:

    fileNameResult.name = files[0].name
    

    在将其添加到表单数据之前。

    【讨论】:

    • 那么文件仍然没有保存在正确的文件类型下,我无法在firebase中打开它。节点中的文件操作可能有问题?
    • 你能console.log(fileNameResult)告诉我里面有什么吗?
    • 它包含 {size: 564063, type: "application/pdf"} 和一些 proto_: Blob 对象。
    • 我在票里加了一张图片
    猜你喜欢
    • 2020-05-23
    • 2020-11-20
    • 2014-06-13
    • 2015-07-05
    • 2022-11-17
    • 2019-01-23
    • 2023-03-24
    • 2013-06-09
    • 2012-03-18
    相关资源
    最近更新 更多