我正在尝试使用nodejs和multer上传pdf到服务器,但有一个问题。a从ejs模板发送一个文件,它必须保存在磁盘上名为上传的文件夹中,文件名更改为特定名称。但是Multer中间件不工作,没有创建文件夹,没有更改文件名,这是怎么回事
有部分代码。
ejs文件
<form enctype="multipart/form-data">
<input type="text" placeholder="Book Name" id="name" />
<input type="text" placeholder="Author " id="author" />
<input type="text" placeholder="Buy link" id="link" />
<input type="text" placeholder="Book description" id="desc" />
<input type="file" name="pdf" id="pdf" placeholder="upload file" />
<button type="submit">Add</button>
</form>
<script>
// const multer = import("multer");
// const upload = multer({ dest: "./public/data/uploads/" });
let form = document.querySelector("form");
form.addEventListener("submit", async (e) => {
let bookName = document.getElementById("name").value;
let bookAuthor = document.getElementById("author").value;
let bookLink = document.getElementById("link").value;
let bookDesc = document.getElementById("desc").value;
let pdf = document.getElementById("myfile").files[0].name;
e.preventDefault();
try {
const res = await fetch("/addBooks", {
method: "POST",
body: JSON.stringify({
bookName,
bookAuthor,
bookDesc,
bookLink,
pdf,
}),
headers: { "Content-Type": "application/json" },
});
</script>
中间件:
onst storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "upload");
},
filename: function (req, file, cb) {
cb(null, Date.now() + "-" + file.originalname);
console.log(destination, filename);
},
});
const upload = multer({ storage });
route.post("/addBooks", upload.single("pdf"), addBook);
邮政职能
let addBook = async (req, res) => {
console.log("reqbody >> ", req.body);
let { bookName, bookAuthor, bookDesc, bookLink, pdf } = req.body;
try {
let _book = await books.create({
name: bookName,
author: bookAuthor,
description: bookDesc,
buyLink: bookLink,
pdf:pdf,
});
if (_book) {
res.status(200).send({ msg: "success" });
}
} catch (error) {
logger.error("system crashed try again ");
res.status(400).send({ msg: "Wrong" });
}
};
2条答案
按热度按时间prdp8dxp1#
发送文件时,必须以表单的形式发送,信息来自req.file,而不是req.body
uoifb46i2#
要上传文件,您需要提交
multipart/form-data
请求,而不是JSON,您可以使用FormData。您可以轻松地从HTML表单构造FormData有效负载,然后在服务器上从
req.file
读取pdf
,而不是body。(您可以使用req.file.filename
添加文件名)。试试这个(你需要添加
name
属性,它将对应于服务器上req.body
的属性):HTML:
服务器: