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 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?