为什么我强大的代码不能与 node js 一起使用(上传图像并让代码根据用户的操作做出响应)?

Why doesn't my formidable code work with node js (upload an image and have the code respond according to the user's action)?

提问人:IsaBedoya06 提问时间:7/24/2023 最后编辑:DarkBeeIsaBedoya06 更新时间:7/28/2023 访问量:45

问:

我正在观看 bluuweb 的节点课程,他们在其中进行了实践练习。

这是第 39 分钟的代码,具体如下:

const formidable = require("formidable");

const cambiarFotoPerfil = (req, res) => {
    const form = new formidable.IncomingForm();
    form.maxFileSize = 5 * 1024 * 1024;

    form.parse(req, async (err, fields, files) => {

        try {
            
            if (err) {
                throw new Error('Falló formidable')
            }

            console.log(fields);
            console.log(files.myFile)

            const file = files.myFile;

            if(file.originalFilename === ""){
                throw new Error('No se seleccionó ninguna imagen')
            }
            
            if(!['image/jpeg', 'image/png'].includes(file.mimetype)){
                throw new Error('Por favor agrega una imagen con formato .jpg o png')
            }

            if(file.size > 5 * 1024 * 1024){
                throw new Error('La imagen debe ser de máximo 5MB')
            }

            req.flash("mensajes", [{ msg: "Ya se subió la imagen" }]);
            return res.redirect('/perfil');
            
        } catch (error) {
            console.log(error);
            req.flash("mensajes", [{ msg: error.message }]);
            return res.redirect("/perfil");
        }
    });
};

module.exports = {
    formPerfil,
    cambiarFotoPerfil
}

这是 HTML:

<form action="/perfil?_csrf={{csrfToken}}" method="post" enctype="multipart/form-data">
    {{!-- <input type="hidden" name="_csrf" value="{{csrfToken}}" /> --}}
    <input class="form-control form-control-sm mb-2" type="file" id="formFileSm" name="myFile" />
    <button class="btn btn-dark">Cambiar foto</button>
</form>

问题是,如果我不发送任何文件,它会跳转到错误“失败很棒”并忽略其余部分。当我发送或文件时,我收到错误 ,尽管它应该符合格式。jpgpngPlease add an image in .jpg or png format

我试图删除以下代码

if (err) {
      throw new Error('Falló formidable')
}

但它跳到了一个错误

无法读取 undefined 的属性(读取“originalFilename”)

我还尝试卸载 formidable 并重新安装它,但没有任何改变。我不知道这是语法问题还是一个可怕的错误。

JavaScript 节点 .js 强大

评论


答:

0赞 IsaBedoya06 7/25/2023 #1

我的问题的解决方案

最后,我找到了解决方案。在我添加了.const file = files.myFile[0];[0]

这是我的新脚本:

const {formidable} = require("formidable");

const cambiarFotoPerfil = (req, res) => {

    const form = formidable({});
    form.maxFileSize = 5 * 1024 * 1024; // 5MB

    form.parse(req, async (err, fields, files) => {
        if (err) {
            req.flash("mensajes", [{ msg: "Falló formidable" }]);
            return res.redirect("/perfil");
        }
    
        // HERE the [0] was added as mentioned above
        const file = files.myFile[0];

        try {
            // console.log(fields);
            console.log(file)

            console.log(file.originalFilename)

            if(file.originalFilename === ""){
                throw new Error('No se seleccionó ninguna imagen')
            }
            
            if(!['image/jpeg', 'image/png'].includes(file.mimetype)){
                throw new Error('Por favor agrega una imagen con formato .jpg o png')
            }

            if(file.size > 5 * 1024 * 1024){
                throw new Error('La imagen debe ser de máximo 5MB')
            }

            req.flash("mensajes", [{ msg: "Ya se subió la imagen" }]);
            return res.redirect('/perfil');
            
        } catch (error) {
            console.log(error);
            req.flash("mensajes", [{ msg: error.message }]);
            return res.redirect("/perfil");
        }
    });
};

评论

0赞 AztecCodes 7/28/2023
如果这是您问题的解决方案,请将此答案标记为正确答案。