现场和文件上的服务员不开火

busboy on field and on file not firing

昨天还运行,现在没有对代码做任何修改就停止了。怎么回事?

客户端

async function uploadFile(file) {
    let formData = new FormData();

    formData.append("recordUid", recordUid);
    formData.append("fieldUid", fieldUid);
    formData.append("file", file);

    await fetchPostFormData("/api/files", formData);
}

async function fetchPostFormData(url, formData) {);
    try {
        let result = await (
            await fetch(url, {
                method: "POST",
                withCredentials: true,
                credentials: "include",
                headers: {
                    Authorization: localStorage.getItem("token"),
                },
                body: formData,
            })
        ).json();

        return result;
    } catch (err) {
        return err;
    }
}

服务器

router.post("/api/files", async (req, res, next) => {
    try {
        console.log("starting upload..."); // <------------------- THIS ONE IS LOGGED

        let bb = busboy({
            headers: req.headers,
            limits: {
                fileSize: 20 * 1024 * 1024, // 20 mb
            },
        });

        let fields = {};

        // Get any text values
        bb.on("field", (fieldname, val, fieldnameTruncated, valTruncated) => {

            console.log("on.field", fieldname, val); // <------------------ NOT FIRING

            fields[fieldname] = val;
        });

        bb.on("file", (fieldname, file, filename, encoding, mimetype) => {

            console.log("on.file"); // <----------------------------------- NOT FIRING

            let parts = filename.filename.split(".");
            let name = parts[0];
            let extension = parts[parts.length - 1];

            let finalName = `${+new Date()}-${name}.${extension}`;
            let filePath = `${filesFolderPath}${finalName}`;

            // Open writeable stream to path
            let writeStream = fs.createWriteStream(filePath);

            // Pipe the file to the opened stream
            file.pipe(writeStream);

            // Check for errors
            writeStream.on("error", (err) => {
                console.log(err);
            });

            writeStream.on("close", async (err) => {
                let sizeBytes = fs.statSync(filePath).size;
            });
        });

        bb.on("finish", () => {
            res.status(200).send({ success: true });
        });
    } catch (err) {
        next(err);
    }
});

设法解决了。

问题是最后缺少 req.pipe(bb)

        // previous code... ^^^^^

        bb.on("finish", () => {
            res.status(200).send({ success: true });
        });

        req.pipe(bb)  // <------------- THIS SHIT RIGHT HERE

    } catch (err) {
        next(err);
    }
});