首页 > 解决方案 > 如何在formdata上附加多个文件输入

问题描述

我必须使用表单数据发送多个文件,但我的代码不起作用,谁能告诉我哪里出错了。

$('#fileupload').on('change', function() {
  var to_user_id = $(this).data('touserid');
  var chat_id = $(this).data('chat_id');
  var formData = new FormData();
  $.each($('input[type=file]')[0].files, function(i, value) {
    formData.append('file[' + i + ']', value.files[0]);
  });
  //console.log(formData);
  formData.append('to_user_id', to_user_id);
  formData.append('chat_id', chat_id);
  $.ajax({
    url: 'upload.php',
    type: 'POST',
    data: formData,
    dataType: 'json',
    processData: false,
    contentType: false,
    cache: false,
    success: function(data) {
      //console.log(data);
    }
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" name="upload_form" id="upload_form" enctype="multipart/form-data" action="upload.php">
  <input type="file" name="fileupload[]" id="fileupload" multiple data-touserid="'+to_user_id+'" data-chat_id="'+getdata+'">
</form>

标签: javascriptphpjqueryhtml

解决方案


您必须在表单数据中传递值

$.each($('input[type=file]')[0].files, function(i, value){
    formData.append('file['+i+']', value); // change this to value
});

我使用的示例代码

$.each($('#upload_screenshot')[0].files,function(key,input){
formData.append('upload_screenshot[]', input);
});

推荐阅读