0

我有一个 node/express 应用程序,我想将图像上传添加到订单。

我可以使用操作链接将 html 表单发布到 POST,但我也希望我的 javascript 文件能够获取所有其余的表单数据并将其发送到不同的发布路径以创建数据库条目整个订单。

这是我的 HTML,可用于发送帖子和图像,但由于事件默认行为而重新加载页面。

<form id="editOrderForm" method="POST" action="/uploadphoto" enctype='multipart/form-data' >

                        <div class="form-row">
                          <div class="form-group col-md-3">
                            <label for="orderWarranty">Warranty Type</label>
                            <input type="text" class="form-control" id="orderWarranty" placeholder="Warranty Type">
                          </div>
                          <div class="form-group col-md-3">
                            <label for="orderAppliance">Appliance</label>
                            <input type="text" class="form-control" id="orderAppliance" placeholder="Appliance">
                          </div>
                          <div class="form-group col-md-3">
                            <label for="orderBrand">Brand</label>
                            <input type="text" class="form-control" id="orderBrand" placeholder="Brand">
                          </div>
                          <div class="form-group col-md-3">
                            <label for="orderModel">Model</label>
                            <input type="text" id="orderModel" class="form-control" placeholder="">
                          </div>
                        </div>

  <div class="modal-body mx-6" id="editOrderDiv">
    <div class="col-md-3">
      <label for="image-upload">Upload Image</label>
       <input type="file" accept="image/*" id="imageupload" name="imageupload">
    </div>
  </div>
  <div class="modal-footer d-flex justify-content-center">
      <input type="submit" class="btn btn-primary" id="ordersubmit"></input>
  </div>
 </div>
</form>

我需要的是以下代码在表单提交后也运行,以发表另一篇文章。

如果我尝试从我的 js 文件发布到我的上传路线,无论我做什么,它都会发送内容类型为 application/x-www-form-urlencoded 而不是 multipart/form-data 的帖子,所以 multer 不接受它.

有没有办法在我将请求发送到后端之前设置内容类型?

$("#editOrderForm").on("submit", function handleFormSubmit(event) {
    event.preventDefault();

    function submitOrder(Order) {
      $.post("/api/orders/" + currentOrder.id, Order, function () {
        getOrders(orderCategorySelect.val());
      });
    };

4

1 回答 1

0

我并没有真正使用 jQuery,但我认为您想在对$.post.

查看jquery 文档,其中也提到了 ajax 设置

通过浏览文档,听起来您需要在设置中创建一个带有正确标头的 Ajax 请求,然后使用该请求来执行实际的 POST。

就像是:

let request = $.post({
  "header" : "multipart/form-data"
})

request("/api/orders", [rest of code here])
于 2019-05-02T22:46:11.133 回答