我想將檔案名列印到控制臺,但它給了我一個錯誤:當我用檔案發布我的服務器的路徑時
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")}`);
});
uj5u.com熱心網友回復:
您沒有使用 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/383081.html
