【问题标题】:How to use express-uploadfiles?如何使用快速上传文件?
【发布时间】:2022-01-19 16:43:49
【问题描述】:

我想将文件名打印到控制台,但它给了我一个错误: 当我用文件发布我的服务器的路径时

TypeError: Cannot read properties of undefined (reading 'file')

我的代码是:

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const fileUpload = require("express-fileupload");

// SETTINGS
app.set("port", process.env.PORT || 3000);

// MIDDLEWARES
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use((req, res, next) => {
    console.log(`${req.method} - ${req.url}`);
    next();
});

// ROUTES
app.post("/upload", (req, res) => {
    const file = req.files.file;
    console.log(file.name);
});

app.listen(app.get("port"), () => {
    console.log(`Server on port ${app.get("port")}`);
});

【问题讨论】:

    标签: node.js express file-upload


    【解决方案1】:

    您没有使用 fileUpload 中间件。将文件添加到请求方法的中间人。

    app.use(fileUpload())
    

    在上传处理程序之前添加它,与使用 bodyParser 中间件的方式相同。

    要上传文件,您还需要确保 html 表单使用

    encType="multipart/form-data"
    

    您可以查看文档:https://github.com/richardgirges/express-fileupload

    还有基本代码示例:https://github.com/richardgirges/express-fileupload/tree/master/example#basic-file-upload

    【讨论】:

    猜你喜欢
    • 2018-01-28
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    相关资源
    最近更新 更多