如何使用jQuery将所选文件传递到php脚本


How to pass selected file to php script using jQuery?

我使用以下表单:

<form id="form-attachment" action="" method="post" enctype="multipart/form-data">
    <input name="attachment" type="file" />
    <input type="submit" />
</form>

这就是我使用jQuery所做的:

$('body').on('submit', '#form-attachment', function(e) {
    e.preventDefault();
    var data = $(this).serialize();
    console.log('fine', data);
    var url = 'imageupload.php';
    $.ajax({
        type : "POST",
        url : url,
        data : data,
        success : function(response) {
            console.log('success: ' + response);
        },
        complete : function(response) {
            console.log('complete: ', response);
        },
        error: function(response) { 
            console.log('error: ', response); 
        }
    });
});

这是我的imageupload.php文件:

$response = array();
$response["c"] = isset($_FILES["attachment"]);
echo json_encode($response);

这是submit():控制台上的结果

成功:{"c":false}

那么,怎么了?为什么我的文件根本不可见?

您可以使用FormData对象,如下所示。。

$('body').on('submit', '#form-attachment', function(e) {
var data = new FormData(jQuery('#form-attachment')[0]);
 jQuery.ajax({
   type: "post",
   contentType: false,
   processData: false,
   url: jQuery(this).attr('action'),
   dataType: "json",
   data: data,
   success: function (r) {
    // Success Handeling
   }
  });
});

注意:-不需要像其他答案所建议的那样附加任何内容该方法应像在普通http形式的POST方法中一样传递所有输入字段。

使用FormData对象。

以下是如何通过jQuery ajax请求发送文件的示例:

$(document).on('change', 'input[type=file]', function() {
  formData = new FormData;
  formData.append('file', $(this)[0].files[0]);
  $.ajax {
    url: '/upload-url',
    data: formData,
    type: 'post',
    processData: false,
    contentType: false,
    success: function(data) {
      console.log(data);
    }
  }
});

在您的情况下,您应该首先序列化表单,将序列化的数据附加到formData对象。然后从文件字段中获取文件,并将其附加到同一个formData对象中。最后通过ajax发送formData对象。