拖拽掉落&上传文件或图片 - HTML5,AJAX

时间:2013-10-11 00:39:17

标签: php ajax html5 file-upload drag-and-drop

我一直在寻找许多关于如何使用drag& amp; drop - 显然该技术正在使用ajax和html5。 问题是,由于我对ajax的了解有限,我不能或根本不知道如何上传作品。 以网站为例: http://robertnyman.com/html5/fileapi-upload/fileapi-upload.htmlhttp://www.devbridge.com/projects/html5-ajax-file-upload/

如果设法使我的页面看起来就像模型...文件被找到,ajax的响应说文件已经上传并出现在屏幕上的信息,如图像大小,mime类型等。 即使在第一个模型中,图像也以data / base64的形式出现 - 但我又陷入了不知道如何对待和上传自身的循环中。 有人帮忙吗?

主要问题是如何进行调用,可能是文件.php,它将通过$ _POST或我不知道的其他方式发送文件(图像)。

对我来说,理想情况下,第一个例子似乎简单而实用。我们会继续努力吗?

外观:

<h3>Choose file(s)</h3>
            <p>
                <input id="files-upload" type="file" multiple>
            </p>
            <p id="drop-area">
                <span class="drop-instructions">or drag and drop files here</span>
                <span class="drop-over">Drop files here!</span>
            </p>

            <ul id="file-list">
                <li class="no-items">(no files uploaded yet)</li>
            </ul>
            <script>
                (function () {
                    var filesUpload = document.getElementById("files-upload"),
                        dropArea = document.getElementById("drop-area"),
                        fileList = document.getElementById("file-list");

                    function uploadFile (file) {
                        var li = document.createElement("li"),
                            div = document.createElement("div"),
                            img,
                            progressBarContainer = document.createElement("div"),
                            progressBar = document.createElement("div"),
                            reader,
                            xhr,
                            fileInfo;

                        li.appendChild(div);

                        progressBarContainer.className = "progress-bar-container";
                        progressBar.className = "progress-bar";
                        progressBarContainer.appendChild(progressBar);
                        li.appendChild(progressBarContainer);

                        /*
                            If the file is an image and the web browser supports FileReader,
                            present a preview in the file list
                        */
                        if (typeof FileReader !== "undefined" && (/image/i).test(file.type)) {
                            img = document.createElement("img");
                            li.appendChild(img);
                            reader = new FileReader();
                            reader.onload = (function (theImg) {
                                return function (evt) {
                                    theImg.src = evt.target.result;
                                };
                            }(img));
                            reader.readAsDataURL(file);
                        }

                        // Uploading - for Firefox, Google Chrome and Safari
                        xhr = new XMLHttpRequest();

                        // Update progress bar
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                progressBar.style.width = (evt.loaded / evt.total) * 100 + "%";
                            }
                            else {
                                // No data to calculate on
                            }
                        }, false);

                        // File uploaded
                        xhr.addEventListener("load", function () {
                            progressBarContainer.className += " uploaded";
                            progressBar.innerHTML = "Uploaded!";
                        }, false);

                        xhr.open("post", "upload.php", true);

                        // Set appropriate headers
                        xhr.setRequestHeader("Content-Type", "multipart/form-data");
                        xhr.setRequestHeader("X-File-Name", file.name);
                        xhr.setRequestHeader("X-File-Size", file.size);
                        xhr.setRequestHeader("X-File-Type", file.type);

                        // Send the file (doh)
                        xhr.send(file);

                        // Present file info and append it to the list of files
                        fileInfo = "<div><strong>Name:</strong> " + file.name + "</div>";
                        fileInfo += "<div><strong>Size:</strong> " + parseInt(file.size / 1024, 10) + " kb</div>";
                        fileInfo += "<div><strong>Type:</strong> " + file.type + "</div>";
                        div.innerHTML = fileInfo;

                        fileList.appendChild(li);
                    }

                    function traverseFiles (files) {
                        if (typeof files !== "undefined") {
                            for (var i=0, l=files.length; i<l; i++) {
                                uploadFile(files[i]);
                            }
                        }
                        else {
                            fileList.innerHTML = "No support for the File API in this web browser";
                        }   
                    }

                    filesUpload.addEventListener("change", function () {
                        traverseFiles(this.files);
                    }, false);

                    dropArea.addEventListener("dragleave", function (evt) {
                        var target = evt.target;

                        if (target && target === dropArea) {
                            this.className = "";
                        }
                        evt.preventDefault();
                        evt.stopPropagation();
                    }, false);

                    dropArea.addEventListener("dragenter", function (evt) {
                        this.className = "over";
                        evt.preventDefault();
                        evt.stopPropagation();
                    }, false);

                    dropArea.addEventListener("dragover", function (evt) {
                        evt.preventDefault();
                        evt.stopPropagation();
                    }, false);

                    dropArea.addEventListener("drop", function (evt) {
                        traverseFiles(evt.dataTransfer.files);
                        this.className = "";
                        evt.preventDefault();
                        evt.stopPropagation();
                    }, false);                                      
                })();
            </script>

我的php是一个简单的帖子数据示例,经过测试和运行。像这样:

    <?php


$uploadpath = 'uploads/';   // diretorio para guardar as imagens
$max_size  = 1020;                      // tamanho maximo do arquivo, em KiloBytes
$alwidth   = 901;                       // largura maxima, em pixels
$alheight  = 901;                       // altura maxima, em pixels
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'png');        // extensoes permitidas

if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1) {
  $uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);       // pega o nome do arquivo
  $sepext = explode('.', strtolower($_FILES['fileup']['name']));
  $type = end($sepext);       // pega extensao
  list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']);     // pega altura e largura da imagem
  $err = '';         // para guardar os erros

  // Checa se o arquivo tem a extensao permitida, tamanho, largura e altura
  if(!in_array($type, $allowtype)) $err .= 'O arquivo: <b>'. $_FILES['fileup']['name']. '</b> tem uma extensão não permitida.';
  if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>O tamanho máximo do arquivo deve ser: '. $max_size. ' KB.';
  if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>A Largura x Altura máxima deve ser: '. $alwidth. ' x '. $alheight;

  // Se não tem erros, faz upload da imagem, senão, mostra os erros
  if($err == '') {
    if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
        echo "Tudo ok";
    }
    else echo '<b>Erro ao fazer upload de arquivos na função de upload.</b>';
  }
  else echo $err;  
}

?>

那么,我该怎么做呢?提前谢谢。

0 个答案:

没有答案