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

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

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 :

        &lt;form action=&quot;&quot; id=&quot;ad-bis&quot;&gt;
          &lt;div class=&quot;form-group&quot;&gt;
            &lt;label&gt;INTRODU NUMEle BISERICII&lt;/label&gt;
            &lt;input
              type=&quot;text&quot;
              name=&quot;biserica&quot;
              id=&quot;biserica&quot;
              class=&quot;form-control&quot;
            /&gt;
            &lt;span id=&quot;error_biserica&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
          &lt;/div&gt;
          &lt;div class=&quot;form-group&quot;&gt;
            &lt;label&gt;INTRODU ORASUL&lt;/label&gt;
            &lt;input type=&quot;text&quot; name=&quot;oras&quot; id=&quot;oras&quot; class=&quot;form-control&quot; /&gt;
            &lt;span id=&quot;error_oras&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
          &lt;/div&gt;
          &lt;div class=&quot;form-group&quot;&gt;
            &lt;label&gt;INTRODU ADRESA&lt;/label&gt;
            &lt;input type=&quot;text&quot; name=&quot;adresa&quot; id=&quot;adresa&quot; class=&quot;form-control&quot; /&gt;
            &lt;span id=&quot;error_adresa&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
          &lt;/div&gt;
          &lt;div class=&quot;form-group&quot;&gt;
            &lt;label&gt;INTRODU NUME PREOT&lt;/label&gt;
            &lt;input type=&quot;text&quot; name=&quot;preot&quot; id=&quot;preot&quot; class=&quot;form-control&quot; /&gt;
            &lt;span id=&quot;error_preot&quot; class=&quot;text-danger&quot;&gt;&lt;/span&gt;
          &lt;/div&gt;
          &lt;div class=&quot;form-group&quot;&gt;
            &lt;label for=&quot;poza&quot;&gt;ADAUGA POZA&lt;/label&gt;
            &lt;input type=&quot;file&quot; id=&quot;poza&quot; /&gt;
          &lt;/div&gt;
          &lt;div class=&quot;form-group&quot; align=&quot;center&quot;&gt;
            &lt;button type=&quot;submit&quot; name=&quot;save&quot; id=&quot;save&quot; class=&quot;btn btn-info&quot;&gt;
              SALVARE
            &lt;/button&gt;
          &lt;/div&gt;
        &lt;/form&gt;

in my js file i created submit function:

adBis.addEventListener(&quot;submit&quot;, async e =&gt; {
  e.preventDefault();
  const data = new FormData();
  data.append(
    &quot;data&quot;,
    JSON.stringify({
      nume: document.querySelector(&quot;#biserica&quot;).value,
      oras: document.querySelector(&quot;#oras&quot;).value,
      adresa: document.querySelector(&quot;#adresa&quot;).value,
      preot: document.querySelector(&quot;#preot&quot;).value,
      uid: localStorage.getItem(&quot;uid&quot;)
    })
  );
  data.append(&quot;poza&quot;, _(&quot;#poza&quot;).files[0]);
  console.log(data);
  const res = await await fetch(&quot;http://localhost:8080/api/site/adaugare&quot;, {
    method: &quot;POST&quot;,
    body: data
  });
  const serverData = await res.json();
  console.log(res, serverData);
  _(&quot;.info&quot;).style.display = &quot;none&quot;;
  if (!serverData.success) {
    afisareEroare(data.msg);
  }
  console.log(&quot;ok&quot;);
  await afisRezultate(localStorage.getItem(&quot;uid&quot;));
});

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

const multer = require(&quot;multer&quot;);
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, &quot;../images&quot;);
  },
  filename: function(req, file, cb) {
    cb(null, file.fieldname + &quot;_&quot; + Date.now() + &quot;_&quot; + file.originalname);
  }
});

const upload = multer({
  storage: storage
}).array(&quot;imgUploader&quot;, 3);

outer.post(&quot;/adaugare&quot;, (req, res) =&gt; {
  console.log(req.body);
  res.json({ msg: &quot;ok&quot; });
  /*
 
    */
});

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(&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:

确定