未设置 PHP '$_FILES' 上传文件

Uploading files using PHP `$_FILES` is not set?

本文关键字:文件 FILES 设置 PHP      更新时间:2023-09-26

所以我一直在为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']

在准备 AJAX 请求时缺少以下内容:

formData.append('image', $('input[type=file]')[0].files[0]);