在admin中上传wordpress ajax文件

时间:2015-02-14 08:45:49

标签: php jquery ajax wordpress file-upload

建立一个插件,我想在wordpress管理区域使用ajax上传文件。但是使用formdata发送的文件不会转到你发送给的php文件。 我的HTML代码:

<form action="#" enctype="multipart/form-data" id="file_upload_form"  type="post">
    <div id="browse" class="col-md-6 col-sm-6">
        <i class="fa fa-file-video-o col-md-3 col-sm-3"> </i>
        <span class="col-md-9 col-sm-9">BROWSE  VIDEOS</span>
        <input type="file" name="video_browse" id="video_browse"/>
    </div>
    <div id="upload" class="col-md-6 col-sm-6">
        <i class="fa fa-upload col-md-3 col-sm-3"></i>
        <span class="col-md-9 col-sm-9">UPLOAD</span>
        <input type="submit" value="UPLOAD"  name="video_upload" id="video_upload"/>
    </div>
    <div class="progress col-md-12 col-sm-12">
        <div class="progress-bar progress-bar-striped  active " style="width: 45%"></div>
    </div>
</form>

我的php代码(所有ajax请求的单独php文件,我将其包含在主插件文件中):

<?php
function test(){   
    $message = '';
    $permittedTypes = array(
        'video/mp4',
        'video/webm',
        'video/ogg'
    );
    $destination = __DIR__ . '/all_videos/' ;
    if(!empty($_FILES['video_browse'])){
        if(in_array($_FILES['video_browse']['type'], $permittedTypes)){
            if(!file_exists($destination . $_FILES['video_browse']['name']))  {
                move_uploaded_file($_FILES['video_browse']['tmp_name'],  $destination . $_FILES['video_browse']['name']);
                    $message="upload was successfull.";
            }else{
                    $message = $_FILES['video_browse']['name']. ' already exists in the directory.';
                }
        }  
    }        
    die();
}

add_action('wp_ajax_testingAjax','test');
?> 

和我的js文件:

jq("#file_upload_form").submit(function(e){

    e.preventDefault();

    var x = jq("#video_browse")[0].files;
    var form_data = new FormData();

    form_data.append('video_browse',x);

    jq.ajax({       
        type: "POST",
        url: ajaxurl,
        data: form_data + "&action=testingAjax",
        success: function(response){

        }

    });

});

2 个答案:

答案 0 :(得分:1)

jq("#file_upload_form").submit(function(e){

    e.preventDefault();

    var file = document.getElementById("video_browse");

    var data = new FormData();
    data.append('video_browse', file.files[0]);
    data.append('action','testingAjax');

    var ajax = new XMLHttpRequest();
    ajax.open('post',ajaxurl);
    ajax.send(data);

});

答案 1 :(得分:0)

您需要在ajax函数上设置一些选项才能使其正常工作:

form_data.append('action', 'testingAjax');
jQuery.ajax({
            url: 'ajaxurl', // check this is correct path
            type: 'POST',
            data: form_data,
            cache: false,
            contentType: false,
            processData: false,

            success: function(data){
                console.log(data);
                $('#response').html(data);// or whatever
            }
        });