我的下面的代码
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const path = require("path");
const bodyParser = require("body-parser");
下面是multer的配置。
const multer = require("multer");
const upload = multer({ dest: 'uploads/'});
编辑:1。 还尝试了这种配置,而不是直接上传变量。但这也不起作用。
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./uploads/");
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
if (file.mimetype === "image/jpeg" || file.mimetype === "/image/png") {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
产品添加表单处理。 在这里,我正在处理表单,console.log总是返回undefined。
router.post("/productadd", upload.single("image"), (req, res) => {
console.log(req.file);
const newProduct = {
imagePath: "https://source.unsplash.com/random/480*480",
title: req.body.title,
description: req.body.description,
price: req.body.price
};
new Products(newProduct).save().then(product => {
res.redirect("/products");
});
});
这是我上传文件的表格
<form action="/productadd" Method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" placeholder="Enter the Title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="" cols="30" rows="10" class="form-control" placeholder="Enter the content"></textarea>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="number" class="form-control" name="price" placeholder="Enter the Price">
</div>
<div class="form-group">
<label for="image">Choose an Image:</label>
<input type="file" class="form-control" name="image" />
</div>
<button class="btn btn-primary btn-sm" type="submit">Submit</button>