英文:
send multiple form data to express API with multer
问题
我想发送包含文件的表单数据到我的Express API,以将教堂添加到我的数据库中,并且我想上传教堂的详细信息和一张图片。
这是我的HTML表单:
<form action="" id="ad-bis">
<div class="form-group">
<label>INTRODU NUMEle BISERICII</label>
<input
type="text"
name="biserica"
id="biserica"
class="form-control"
/>
<span id="error_biserica" class="text-danger"></span>
</div>
<!-- 其他表单字段... -->
<div class="form-group">
<label for="poza">ADAUGA POZA</label>
<input type="file" id="poza" />
</div>
<div class="form-group" align="center">
<button type="submit" name="save" id="save" class="btn btn-info">
SALVARE
</button>
</div>
</form>
在我的JavaScript文件中,我创建了提交函数:
adBis.addEventListener("submit", async (e) => {
e.preventDefault();
const data = new FormData();
data.append(
"data",
JSON.stringify({
nume: document.querySelector("#biserica").value,
oras: document.querySelector("#oras").value,
adresa: document.querySelector("#adresa").value,
preot: document.querySelector("#preot").value,
uid: localStorage.getItem("uid"),
})
);
data.append("poza", _("#poza").files[0]);
const res = await fetch("http://localhost:8080/api/site/adaugare", {
method: "POST",
body: data,
});
const serverData = await res.json();
// 处理服务器响应...
});
然后,我使用Multer在Express中创建了上传文件的端点:
const multer = require("multer");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "../images"); // 请确保此目录存在
},
filename: function (req, file, cb) {
cb(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
},
});
const upload = multer({
storage: storage,
}).single("poza"); // 使用.single()表示只上传一个文件
router.post("/adaugare", (req, res) => {
upload(req, res, (err) => {
if (err) {
// 处理上传错误
return res.status(500).json({ error: err.message });
}
// req.body 中现在应该包含表单数据
console.log(req.body);
res.json({ msg: "ok" });
});
});
请确保在Express端点中使用upload
中间件来处理文件上传,并将其配置为.single("poza")
以处理名为"poza"的文件字段。这样,您应该能够在req.body
中访问表单数据。如果有任何上传错误,将它们处理并返回适当的错误响应。
英文:
I want to send form data including a file to my express API for adding churches in my database and i want to upload church details and an image for this.
this is my HTML form :
<form action="" id="ad-bis">
<div class="form-group">
<label>INTRODU NUMEle BISERICII</label>
<input
type="text"
name="biserica"
id="biserica"
class="form-control"
/>
<span id="error_biserica" class="text-danger"></span>
</div>
<div class="form-group">
<label>INTRODU ORASUL</label>
<input type="text" name="oras" id="oras" class="form-control" />
<span id="error_oras" class="text-danger"></span>
</div>
<div class="form-group">
<label>INTRODU ADRESA</label>
<input type="text" name="adresa" id="adresa" class="form-control" />
<span id="error_adresa" class="text-danger"></span>
</div>
<div class="form-group">
<label>INTRODU NUME PREOT</label>
<input type="text" name="preot" id="preot" class="form-control" />
<span id="error_preot" class="text-danger"></span>
</div>
<div class="form-group">
<label for="poza">ADAUGA POZA</label>
<input type="file" id="poza" />
</div>
<div class="form-group" align="center">
<button type="submit" name="save" id="save" class="btn btn-info">
SALVARE
</button>
</div>
</form>
in my js file i created submit function:
adBis.addEventListener("submit", async e => {
e.preventDefault();
const data = new FormData();
data.append(
"data",
JSON.stringify({
nume: document.querySelector("#biserica").value,
oras: document.querySelector("#oras").value,
adresa: document.querySelector("#adresa").value,
preot: document.querySelector("#preot").value,
uid: localStorage.getItem("uid")
})
);
data.append("poza", _("#poza").files[0]);
console.log(data);
const res = await await fetch("http://localhost:8080/api/site/adaugare", {
method: "POST",
body: data
});
const serverData = await res.json();
console.log(res, serverData);
_(".info").style.display = "none";
if (!serverData.success) {
afisareEroare(data.msg);
}
console.log("ok");
await afisRezultate(localStorage.getItem("uid"));
});
then i created endpoint in express using multer tu upload file:
const multer = require("multer");
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "../images");
},
filename: function(req, file, cb) {
cb(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
const upload = multer({
storage: storage
}).array("imgUploader", 3);
outer.post("/adaugare", (req, res) => {
console.log(req.body);
res.json({ msg: "ok" });
/*
*/
});
in my console, req.body
is empty how send all data?
I tried with firebase storage but it doesn't work for me.
what I missed?
thanks!
答案1
得分: 1
第一提示:由于您正在使用FormData,您可以将表单传递进去,以自动获取表单中的所有值。
第二,在这里您等待了两次:
const res = await await fetch("http://localhost:8080/api/site/adaugare", [...]
最后,req.body
为空,可能是因为缺少body-parser,或者正如我在这里看到的,您没有添加enctype="multipart/form-data"
属性,没有这个属性,Multer将无法从您的表单获取任何数据。
英文:
First tip: Since you are using FormData you can pass the form in to get automatically all the values in the form.
Second, here you are awaiting twice:
const res = await await fetch("http://localhost:8080/api/site/adaugare", [...]
Lastly req.body
empty is either because of lack of body-parser or, as I see here, you have not added the enctype="multipart/form-data"
attribute, without this Multer won't get any data from your form.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论