0

我一直在查看许多关于如何使用拖放上传图像的网站 - 显然该技术正在使用 ajax 和 html5 。问题是,鉴于我对 ajax 的了解有限,我无法或不知道如何上传作品。用作示例的站点: http ://robertnyman.com/html5/fileapi-upload/fileapi-upload.html 和 http://www.devbridge.com/projects/html5-ajax-file-upload/

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

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

对我来说,理想情况下,第一个示例看起来既简单又实用。我们会努力吗?

看:

<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;  
}

?>

那么,我能做些什么来实现这一目标呢?提前致谢。

4

0 回答 0