首页 > 解决方案 > TypeError:无法读取未定义节点js的属性“名称”

问题描述

我在 index.html 文件上有文件提交表单。选择文件后,我需要说“文件已上传”,否则需要显示“请上传文件”

应用程序.js

    const express = require("express");
    const app = express();
    const http = require("http").Server(app).listen(3000);

    app.use(express.urlencoded());
    app.use(express.json());

    console.log("Server Started");

    app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
    }
    )

    app.post("/", function (req, res) {
    if (req.files) {

        console.log(req.files);
        const file = req.files.filename;
        const filename = file.name;

        if (!filename) {
        res.send("Please select the file to upload");
        }
        else {
        res.send("uploaded");
        }
    }
    })

索引.html

    <div>
    <h1 style="align-content: center">Upload your file here!</h1>
    </div>
    <div >

    <form label="upload" method="post" enctype="multipart/form-data" action="/">
        <label> Enter reference</label>
        <input type="text" name="test_text"></input>
        <br><br>
        <input type="file" name="filename">
        <input type="submit" value="upload">
    </form>
    </div>

错误信息:

TypeError: Cannot read property 'name' of undefined
    at C:\Users\Desktop\LocalGithub\uploadFileLocal-express-fileupload\app.js:24:27

标签: node.jsexpress

解决方案


以下内容来自 express docs:

在 Express 4 中, req.files 默认不再在 req 对象上可用。要访问 req.files 对象上上传的文件,请使用多部分处理中间件,例如 busboy、multer、formidable、multiparty、connect-multiparty 或 pez。

正如它所说,我建议你使用multer因为它更流行且易于使用

编辑:

如果您使用的是“express-fileupload”中间件,则必须通过.use()以下方法加载它:

const express = require("express");
const app = express();
const http = require("http").Server(app).listen(3000);
const fileUpload = require('express-fileupload');
^^^^^

app.use(express.urlencoded());
app.use(express.json());

app.use(fileUpload({
^^^
    useTempFiles : true,
    tempFileDir : '/tmp/'
}));

...

检查文档以获取更多详细信息:


推荐阅读