首页 > 解决方案 > 如何使用 ajax 提交带有文件上传的表单

问题描述

我有一个很长的多步表格。其中有文本输入和上传文件选项。我正在尝试使用 Ajax 将其提交给 PHP。我已经尝试过FormData,但我不确定如何发送其他选择和文本输入字段。

https://developer.mozilla.org/en-US/docs/Web/API/FormData

我怎样才能做到这一点?

const addListingForm = $('#add-listing-form');

addListingForm.on('submit', function (e) {
  console.log('Submitted');

  const formData = new FormData(document.getElementById('add-listing-form'));

  $.ajax({
    url: `${SITE_URL}/private/shared/process`,
    type: 'post',
    data: formData,
    processData: false,
    contentType: false,
    success: function (resp) {
      console.log(resp);
    },
    error: function (err) {
      console.log(err);
    },
  });

  e.preventDefault();
});
<form action="" method="post" enctype="multipart/form-data" id="add-listing-form">
  <input type="text" name="title" id="title" class="custom-input" />
  <input type="text" name="tagline" id="tagline" class="custom-input" />

  <input type="file" name="halal-certificate" class="custom-file-input" id="halal-certificate">

  <input type="file" name="list-photos[]" multiple class="custom-file-input" id="list-photos">

  <button type="submit">
    Submit
  </button>
</form>

标签: javascriptjquery

解决方案


尝试这个

let title = document.getElementById("title").value;
let firstFile= document.getElementById("list-photos[]").files[0];
let formData = new FormData();

formData.append("file1", firstFile);
formData.append("title", title );
//and add more

或者

let title = document.getElementById("title").value;
let firstFile= document.getElementById("list-photos[]").files[0];  // file from input
let req = new XMLHttpRequest();
let formData = new FormData();

formData.append("file1", firstFile);
formData.append("title", title );
                           
req.open("POST", '/upload/image');
req.send(formData);

推荐阅读