使用Ajax在Wordpress中上传视频

时间:2018-09-20 12:09:00

标签: php ajax wordpress

我正在尝试使用Ajax在wordpress中上传视频,但是$ _FILE变量未获取所选文件。我尝试使用Google搜索,但仍然找不到解决方案。请给我一个简单的解决方案。

这是html代码:

    <form class="f1" method="post" enctype="multipart/form-data">
        <label for="file"><span>Filename:</span></label>
        <input id="file" type="file" name="file"/>
        <br />
        <input type="submit" name="submit" value="Submit" class="btn-sub" />
    </form>

我在页脚中使用了JS,因为我需要从这里开始工作。

jQuery(document).ready(function ($) {
   $(".f1").on("submit",function (event) {
     event.preventDefault();
     var id= $("#file").val();
     $.ajax({
        method:'POST',
        url:'<?php echo admin_url('admin-ajax.php');?>',
        data:{action:'my_form',id:id},
        success:function (result) {
        alert(result);
        }
     });
   }); 

function.php代码:

  function my_ajax_form(){

 require_once(ABSPATH . 'wp-admin/includes/image.php');
 require_once(ABSPATH . 'wp-admin/includes/file.php');
 require_once(ABSPATH . 'wp-admin/includes/media.php');

$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma");
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

if (($_FILES["file"]["type"] == "video/mp4")&& in_array($extension,$allowedExts))
{
    if ($_FILES["file"]["error"] > 0)
    {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
    else
    {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

        if (file_exists("wp-content/upload/" . $_FILES["file"]["name"]))
        {
            echo $_FILES["file"]["name"] . " already exists. ";
        }
        else
        {
            //wordpress way of uploading
            media_handle_upload( $_FILES["file"]["name"], 0 );
            //normal php upload
            move_uploaded_file($_FILES["file"]["tmp_name"],
                "wp-content/uploads/" . $_FILES["file"]["name"]);
            echo "fname".$_FILES["file"]["name"];
            echo "ftname".$_FILES["file"]["temp"];
        }
    }

}else
   {
    echo "Invalid file";
   }
  die();
}
add_action('wp_ajax_my_form', 'my_ajax_form');
add_action('wp_ajax_nopriv_my_form','my_ajax_form'); 

0 个答案:

没有答案