拖动文件上传,错误在$ _FILES中

时间:2014-06-05 10:11:46

标签: javascript php jquery

我尝试创建简单的“拖放”文件上传。这是我的代码:

HTML(index.html):

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
  <script src="script.js"></script>

    <form action="upload.php">
      <div id="dropZone">
        Drag File
      </div>
    </form>

JavaScript(script.js):

$(document).ready(function() {

    var dropZone = $('#dropZone'),
        maxFileSize = 1000000; 

    dropZone[0].ondrop = function(event) {
        event.preventDefault();
        dropZone.removeClass('hover');
        dropZone.addClass('drop');

        var file = event.dataTransfer.files[0];


        if (file.size > maxFileSize) {
            dropZone.text('Max size 1mb!');
            dropZone.addClass('error');
            return false;
        }

        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', uploadProgress, false);
        xhr.onreadystatechange = stateChange;
        xhr.open('POST', 'upload.php');
        xhr.setRequestHeader('X-FILE-NAME', file.name);
        xhr.send(file);
        alert(xhr.responseText);
    };

    function uploadProgress(event) {
        var percent = parseInt(event.loaded / event.total * 100);
        dropZone.text('Loading: ' + percent + '%');
    }


    function stateChange(event) {
        if (event.target.readyState == 4) {
            if (event.target.status == 200) {
                dropZone.text('Ok!');
            } else {
                dropZone.text('Error!');
                dropZone.addClass('error');
            }
        }
    }

});

PHP(upload.php):

<?php
$uploaddir = 'upload/';
$uploadfile = $uploaddir.basename($_FILES['file']['name']);
if (!$_FILES)
{
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
}
?>

我的问题是文件无法上传到文件夹中,$ _FILES ['file'] ['tmp_name']为空... 有没有人知道我的错误?

谢谢......

1 个答案:

答案 0 :(得分:1)

试试这个,改变你的状况

if (isset($_FILES['file']))
{
 move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
}