我对 Node.js 和 Express 的学习还比较陌生,最近我开始使用 Multer 包来处理文件上传。我在尝试将传入的图像文件保存到“图像”文件夹时遇到问题,尽管我付出了努力,但它并未按预期工作。
控制器:
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const csrf = require("csurf");
const flash = require("connect-flash");
const multer = require("multer");
const errorController = require("./controllers/error");
const User = require("./models/user");
const MONGODB_URI =
"mongodb+srv://Priyansh16:[email protected]/shop?retryWrites=true&w=majority";
const app = express();
const store = new MongoDBStore({
uri: MONGODB_URI,
collection: "sessions",
});
const csrfProtection = csrf();
// Config object for multer.
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + "-" + file.originalname);
},
});
app.set("view engine", "ejs");
app.set("views", "views");
const adminRoutes = require("./routes/admin");
const shopRoutes = require("./routes/shop");
const authRoutes = require("./routes/auth");
app.use(bodyParser.urlencoded({ extended: false }));
// Multer Middleware
app.use(multer({ storage: fileStorage }).single("image"));
app.use(express.static(path.join(__dirname, "public")));
app.use(
session({
secret: "my secret",
resave: false,
saveUninitialized: false,
store: store,
})
);
// CSRF Middleware
app.use(csrfProtection);
// Flash Messages
app.use(flash());
app.use((req, res, next) => {
if (!req.session.user) {
return next();
}
User.findById(req.session.user._id)
.then((user) => {
if (!user) {
return next();
}
req.user = user;
next();
})
.catch((err) => {
throw new Error(err);
});
});
// Locals
app.use((req, res, next) => {
res.locals.isAuthenticated = req.session.isLoggedIn;
res.locals.csrfToken = req.csrfToken();
next();
});
// Routes
app.use("/admin", adminRoutes);
app.use(shopRoutes);
app.use(authRoutes);
app.get("/500", errorController.get500);
app.use(errorController.get404);
app.use((error, req, res, next) => {
res.redirect("/500");
});
mongoose
.connect(MONGODB_URI)
.then((result) => {
app.listen(3000);
})
.catch((err) => {
console.log(err);
});
在 Multer 中间件中而不是
app.use(multer({ storage: fileStorage }).single("image"));
写:
const upload = multer({
storage: fileStorage,
});
图片上传路径:
app.post('/upload', upload.single('image'), function (req, res, next) {
// req.file is your image
// req.body will hold the text fields, if there were any
})
不要忘记表单中的 enctype="multipart/form-data"。
<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
</form>