javascript - 使用PHP上传文件 `$_FILES`没有设置?

标签 javascript php jquery ajax wordpress

所以我一直在为 WordPress 开发一个插件。
因为我已经制作了一个为我上传文件的应用程序,所以我认为这很容易,但可惜的是,我想不出我做错了什么。

问题是;我的 $_FILES['image'] 未设置。

谁能告诉我我的代码有什么问题,因为我找不到它是什么。

表单

<form action="" method="POST" enctype="multipart/form-data">
            <table class="table ws-form-table">
                <tbody>
                    <tr>
                        <td>
                            Add Text:
                        </td>
                        <td>
                            <input type="text" id="ws-text">
                        </td>
                        <td>
                            <button type="button" class="btn btn-primary ws-add-text ws-add-button">+</button>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Add Image:
                        </td>
                        <td>
                            <input type="file" name="image"><progress></progress>
                        </td>
                        <td>
                            <button type="button" class="btn btn-primary ws-add-image ws-add-button">+</button>
                        </td>
                    </tr>
                </tbody>
            </table>
            <div class="preview-container">
                <div class="preview-strict">
                    <img class="ws-image" src="<?php echo $feat_image; ?>" alt="" style="width: 300px; height: 300px;">
                </div>
            </div>
        </form>

JS

jQuery('.ws-add-image').click(function() {
    var formData = new FormData(jQuery('form')[0]);
    console.log('Click Initiated');
    console.log('Ajax Try...');
    jQuery.ajax({

        url: '../../wp-content/plugins/my-plugin/my-plugin-handler.php',
        type: 'POST',
        xhr: function() {
            var myXhr = jQuery.ajaxSettings.xhr();
            if(myXhr.upload){ 
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
            }
            return myXhr;
        },

        data: formData,

        cache: false,
        contentType: false,
        processData: false,
        error: function() {
            console.log('Error Initiated');
        },
    }).done(function() {
        alert('dsa');
        jQuery('.preview-strict').prepend('<div id="dragHelper" style="display:inline-block; z-index: 999; cursor: move;"><img id="theImg" src="../../wp-content/plugins/my-plugin/images/' + readCookie('image') + '" width="200px" height=200px; /></div>');
        jQuery("#dragHelper").draggable({drag: function(){
            var offset = jQuery(this).offset();
            var xPos = offset.left;
            var yPos = offset.top;
            jQuery('#posX').text('x: ' + xPos);
            jQuery('#posY').text('y: ' + yPos);
        }
        });

        jQuery("#theImg").resizable();

    });
    alert(readCookie('image'));
    console.log('Done!');
});
function progressHandlingFunction(e){
    if(e.lengthComputable){
        jQuery('progress').attr({value:e.loaded,max:e.total});
    }
}

PHP

<?php 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include_once($_SERVER['DOCUMENT_ROOT'].'/test/wp-load.php' );
global $wpdb;
$table_name = $wpdb->prefix . "my-plugin"; 

if(isset($_FILES['image'])) {
    $wty = 'ISSET';
      $sql = $wpdb->get_results("SELECT ID FROM " . $table_name . " ORDER BY ID DESC LIMIT 1");
      echo $_FILES['image']['name'];
      foreach( $wpdb->get_results("SELECT ID FROM " . $table_name . " ORDER BY ID DESC LIMIT 1") as $key => $row) {
          $id = $row->ID;
      }

      $temp = explode(".", $_FILES["image"]["name"]);
      $last = $id . round(microtime(true)) . '.' . end($temp);
      $errors= array();
      $file_name = $_FILES['image']['name'];
      $file_size = $_FILES['image']['size'];
      $file_tmp = $_FILES['image']['tmp_name'];
      $file_type = $_FILES['image']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

      $ext = end((explode(".", $file_name)));

      $expensions= array("jpeg","jpg","png");

      if(empty($errors)==true) {

         move_uploaded_file($file_tmp, ABSPATH . "test/wp-content/plugins/my-plugin/images/" . $last);

      }

      else

      {

         print_r($errors);

      }
}


$cookie_name = "image";
$cookie_value = $wty;
$cookie_exp = time() + (86400 * 30);



setcookie($cookie_name, $cookie_value, $cookie_exp, "/");


?>

这就是它的工作原理:选择图像,单击按钮,运行单击事件,ajax 运行 PHP 文件。 PHP 文件(需要)上传图像,创建带有图像名称的 cookie。图像名称从 cookie 中获取,并在 ajax 完成后将其添加到 DOM。

我尝试查找此内容,但由于某种原因,除了人们说我可能忘记了 enctype="multipart/form-data" 之外,我找不到任何内容。

那我做错了什么?

请记住,这是一个 WordPress 插件。所以这可能与 WordPress 相关。但我不这么认为。

我仍在学习,因此感谢任何改进代码的帮助!

最佳答案

此代码适用于单个或多个文件。

$('.ws-add-image').click(function() {

 var data = new FormData();

 //Append files infos
 jQuery.each($(this)[0].files, function(i, file) {
     data.append('file-'+i, file);
 });

 $.ajax({  
     url: "my_path",  
     type: "POST",  
     data: data,  
     cache: false,
     processData: false,  
     contentType: false, 
     context: this,
     success: function (msg) {
          alert(msg);
      }
  });
});

然后在你的 php 文件中你将使用以下命令获取文件..

$_FILES['file-0']
$_FILES['file-1']

关于javascript - 使用PHP上传文件 `$_FILES`没有设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35867527/

相关文章:

php - 重定向到 url,然后再次重定向到主 url

javascript - 用回车符替换字符 - JavaScript

javascript - 如果与 GeoJSON 层一起使用, map 标签的 zIndex 无效

php - MySQL:通过用户ID获取常用记录

jquery - css code issue using style and div 在线无答案

javascript - 一定范围内的随机整数,不包括一个数

PHP 获取事件 session

php文件重命名循环

jquery - 如何在选择列表上添加限制

jquery - 带有各种 jquery 铃声和口哨的搜索页面