为什么我不能抓取在我的<input type="file">中选择的文件?


Why am I not able to grab the file selected in my <input type="file">?

我正在开发一个WordPress主题,我有一个PHP函数,应该处理和异步请求,为服务器提供JSON和图像。我的表单(为了可读性,去掉了一堆内部HTML)看起来像

       <form method="POST" action="member-update"  enctype="multipart/form-data" id="member-form">
 9">
            <input type="text" name="fullname" value=""> 
            <input type="text" name="title" value="">
            <textarea rows="4" name="bio" form="member-form"></textarea> 
            <input type="text" name="sord" value=""> 
            <input type="file" name="pic">
            <input type="hidden" name="memberAction" value="" />
    </form>

和我的JavaScript用于发出AJAX请求是

        jQuery('.member-update-button').click( function() {
            var parentForm = jQuery(this).closest('form');
            var postData = parentForm.serializeArray();
            jQuery.post( ajaxurl,
                        {'action': 'member_update', 'formStuff' : postData},
                        function(response) { alert('Got this from the server: ' + response); }
                       );
        });

和我的PHP函数,通过WordPress钩子,处理请求开始像

function member_update ( )
{
    // there must be a more elegant way of getting those values out .... 
    $name = $_POST['formStuff'][0]['value'];
    $title = $_POST['formStuff'][1]['value'];
    $bio = $_POST['formStuff'][2]['value'];
    $sord = $_POST['formStuff'][3]['value'];

    $targetFileName = basename($_FILES['pic']['name']);
    $targetFileNameAndPath = 'assets/' . $targetFileName;

我从$_POST['formStuff']数组中获得值,但我没有从$_FILES['pic']['name']中获得任何值。知道我哪里做错了吗?

您需要使用FormData的实例。在您的代码中进行以下更改:

在你的html中添加id属性

<input type="file" name="pic" id="pic">

js代码的变化

jQuery('.member-update-button').click( function() {
   formdata = new FormData();
   formdata.append( 'action', 'member_update' );
   jQuery.each(jQuery('#pic')[0].files, function(i, file) {
       formdata.append('file_to_upload', file);
   });
   jQuery.post( ajaxurl, formdata,function(response) {
      alert('Got this from the server: ' + response); 
   });
});

php函数的最终变化

function member_update()
{
   $file = $_FILES['file_to_upload']['tmp_name'];
}