发送多个表单数据到Express API并使用Multer处理

huangapple go评论149阅读模式
英文:

send multiple form data to express API with multer

问题

我想发送包含文件的表单数据到我的Express API,以将教堂添加到我的数据库中,并且我想上传教堂的详细信息和一张图片。

这是我的HTML表单:

  1. <form action="" id="ad-bis">
  2. <div class="form-group">
  3. <label>INTRODU NUMEle BISERICII</label>
  4. <input
  5. type="text"
  6. name="biserica"
  7. id="biserica"
  8. class="form-control"
  9. />
  10. <span id="error_biserica" class="text-danger"></span>
  11. </div>
  12. <!-- 其他表单字段... -->
  13. <div class="form-group">
  14. <label for="poza">ADAUGA POZA</label>
  15. <input type="file" id="poza" />
  16. </div>
  17. <div class="form-group" align="center">
  18. <button type="submit" name="save" id="save" class="btn btn-info">
  19. SALVARE
  20. </button>
  21. </div>
  22. </form>

在我的JavaScript文件中,我创建了提交函数:

  1. adBis.addEventListener("submit", async (e) => {
  2. e.preventDefault();
  3. const data = new FormData();
  4. data.append(
  5. "data",
  6. JSON.stringify({
  7. nume: document.querySelector("#biserica").value,
  8. oras: document.querySelector("#oras").value,
  9. adresa: document.querySelector("#adresa").value,
  10. preot: document.querySelector("#preot").value,
  11. uid: localStorage.getItem("uid"),
  12. })
  13. );
  14. data.append("poza", _("#poza").files[0]);
  15. const res = await fetch("http://localhost:8080/api/site/adaugare", {
  16. method: "POST",
  17. body: data,
  18. });
  19. const serverData = await res.json();
  20. // 处理服务器响应...
  21. });

然后,我使用Multer在Express中创建了上传文件的端点:

  1. const multer = require("multer");
  2. const storage = multer.diskStorage({
  3. destination: function (req, file, cb) {
  4. cb(null, "../images"); // 请确保此目录存在
  5. },
  6. filename: function (req, file, cb) {
  7. cb(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
  8. },
  9. });
  10. const upload = multer({
  11. storage: storage,
  12. }).single("poza"); // 使用.single()表示只上传一个文件
  13. router.post("/adaugare", (req, res) => {
  14. upload(req, res, (err) => {
  15. if (err) {
  16. // 处理上传错误
  17. return res.status(500).json({ error: err.message });
  18. }
  19. // req.body 中现在应该包含表单数据
  20. console.log(req.body);
  21. res.json({ msg: "ok" });
  22. });
  23. });

请确保在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 :

  1. &lt;form action=&quot;&quot; id=&quot;ad-bis&quot;&gt;
  2. &lt;div class=&quot;form-group&quot;&gt;
  3. &lt;label&gt;INTRODU NUMEle BISERICII&lt;/label&gt;
  4. &lt;input
  5. type=&quot;text&quot;
  6. name=&quot;biserica&quot;
  7. id=&quot;biserica&quot;
  8. class=&quot;form-control&quot;
  9. /&gt;
  10. &lt;span id=&quot;error_biserica&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
  11. &lt;/div&gt;
  12. &lt;div class=&quot;form-group&quot;&gt;
  13. &lt;label&gt;INTRODU ORASUL&lt;/label&gt;
  14. &lt;input type=&quot;text&quot; name=&quot;oras&quot; id=&quot;oras&quot; class=&quot;form-control&quot; /&gt;
  15. &lt;span id=&quot;error_oras&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
  16. &lt;/div&gt;
  17. &lt;div class=&quot;form-group&quot;&gt;
  18. &lt;label&gt;INTRODU ADRESA&lt;/label&gt;
  19. &lt;input type=&quot;text&quot; name=&quot;adresa&quot; id=&quot;adresa&quot; class=&quot;form-control&quot; /&gt;
  20. &lt;span id=&quot;error_adresa&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
  21. &lt;/div&gt;
  22. &lt;div class=&quot;form-group&quot;&gt;
  23. &lt;label&gt;INTRODU NUME PREOT&lt;/label&gt;
  24. &lt;input type=&quot;text&quot; name=&quot;preot&quot; id=&quot;preot&quot; class=&quot;form-control&quot; /&gt;
  25. &lt;span id=&quot;error_preot&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
  26. &lt;/div&gt;
  27. &lt;div class=&quot;form-group&quot;&gt;
  28. &lt;label for=&quot;poza&quot;&gt;ADAUGA POZA&lt;/label&gt;
  29. &lt;input type=&quot;file&quot; id=&quot;poza&quot; /&gt;
  30. &lt;/div&gt;
  31. &lt;div class=&quot;form-group&quot; align=&quot;center&quot;&gt;
  32. &lt;button type=&quot;submit&quot; name=&quot;save&quot; id=&quot;save&quot; class=&quot;btn btn-info&quot;&gt;
  33. SALVARE
  34. &lt;/button&gt;
  35. &lt;/div&gt;
  36. &lt;/form&gt;

in my js file i created submit function:

  1. adBis.addEventListener(&quot;submit&quot;, async e =&gt; {
  2. e.preventDefault();
  3. const data = new FormData();
  4. data.append(
  5. &quot;data&quot;,
  6. JSON.stringify({
  7. nume: document.querySelector(&quot;#biserica&quot;).value,
  8. oras: document.querySelector(&quot;#oras&quot;).value,
  9. adresa: document.querySelector(&quot;#adresa&quot;).value,
  10. preot: document.querySelector(&quot;#preot&quot;).value,
  11. uid: localStorage.getItem(&quot;uid&quot;)
  12. })
  13. );
  14. data.append(&quot;poza&quot;, _(&quot;#poza&quot;).files[0]);
  15. console.log(data);
  16. const res = await await fetch(&quot;http://localhost:8080/api/site/adaugare&quot;, {
  17. method: &quot;POST&quot;,
  18. body: data
  19. });
  20. const serverData = await res.json();
  21. console.log(res, serverData);
  22. _(&quot;.info&quot;).style.display = &quot;none&quot;;
  23. if (!serverData.success) {
  24. afisareEroare(data.msg);
  25. }
  26. console.log(&quot;ok&quot;);
  27. await afisRezultate(localStorage.getItem(&quot;uid&quot;));
  28. });

then i created endpoint in express using multer tu upload file:

  1. const multer = require(&quot;multer&quot;);
  2. const storage = multer.diskStorage({
  3. destination: function(req, file, cb) {
  4. cb(null, &quot;../images&quot;);
  5. },
  6. filename: function(req, file, cb) {
  7. cb(null, file.fieldname + &quot;_&quot; + Date.now() + &quot;_&quot; + file.originalname);
  8. }
  9. });
  10. const upload = multer({
  11. storage: storage
  12. }).array(&quot;imgUploader&quot;, 3);
  13. outer.post(&quot;/adaugare&quot;, (req, res) =&gt; {
  14. console.log(req.body);
  15. res.json({ msg: &quot;ok&quot; });
  16. /*
  17. */
  18. });

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,您可以将表单传递进去,以自动获取表单中的所有值。

第二,在这里您等待了两次:

  1. 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:

  1. const res = await await fetch(&quot;http://localhost:8080/api/site/adaugare&quot;, [...]

Lastly req.body empty is either because of lack of body-parser or, as I see here, you have not added the enctype=&quot;multipart/form-data&quot; attribute, without this Multer won't get any data from your form.

huangapple
  • 本文由 发表于 2020年1月3日 19:02:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定