douye1940 2016-03-08 12:34
浏览 42

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

So I've been developing a plugin for WordPress.
As I already have made an application which uploads files for me, I thought it would be easy but alas, I can't think of what I am doing wrong.

The problem is; my $_FILES['image'] is not set.

Can anyone tell me what is wrong with my code, because I can't find out what it is.

Form

<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, "/");


?>

So this is how it works: Image gets chosen, button gets clicked, click event runs, ajax runs a PHP file. The PHP file (needs to) upload image, creates cookie with image name. Image name gets pulled from cookie, and adds it to the DOM after ajax done.

I've tried to look this up but for some reason I can't find anything but peoples saying that I might be forgetting enctype="multipart/form-data".

So what am I doing wrong?

Keep in mind that this is a WordPress plugin. So it may be something WordPress related. But I don't think so.

I'm still learning so any help with improving the code is appreciated!

  • 写回答

2条回答 默认 最新

  • douyoufan7881 2016-03-08 12:44
    关注

    You are missing following while cooking up your AJAX request:

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器