3

我正在尝试实现拖放图像上传。我在网上找到了一个相当简单的脚本并适应了我的使用。在我的本地安装中,文件上传非常好,但不是在服务器上。从我的调试尝试中,$_SERVER['HTTP_X_FILENAME'] 甚至没有被 php 设置。

我尝试了以下方法: - 确保上传文件夹设置为 755 - 更改 php 临时上传路径并增加允许的最大文件大小

不会发生任何类型的 php 或 js 错误。因为我有 die(print_r($_SERVER)); 在 php 中,我使用 chrome 检查器获得了 $_SERVER 转储,它不包含 HTTP_X_FILENAME 索引。

我的PHP是:

<?php
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);

if ($fn) {

      // AJAX call
      file_put_contents(
        '../usr/photos/' . $fn,
        file_get_contents('php://input')
       );
       echo "$fn uploaded";
       exit();

}
else {
      // form submit
  if(!$_FILES['fileselect']) die(print_r($_SERVER));
  else $files = $_FILES['fileselect'];

  foreach ($files['error'] as $id => $err) {
    if ($err == UPLOAD_ERR_OK) {
        $fn = $files['name'][$id];
        move_uploaded_file(
            $files['tmp_name'][$id],
            '../usr/photos/' . $fn
        );
        echo "<p>File $fn uploaded.</p>";
    }
    }
 }

js如下:

//拖放照片上传(function() {

    // getElementById
    function $id(id) {
        return document.getElementById(id);
    }


    // output information
    function Output(msg) {
        var m = $id("messages");
        m.innerHTML = msg + m.innerHTML;
    }


    // file drag hover
    function FileDragHover(e) {
        e.stopPropagation();
        e.preventDefault();
        e.target.className = (e.type == "dragover" ? "hover" : "");
    }


    // file selection
    function FileSelectHandler(e) {

        // cancel event and hover styling
        FileDragHover(e);

        // fetch FileList object
        var files = e.target.files || e.dataTransfer.files;

        // process all File objects
        for (var i = 0, f; f = files[i]; i++) {
            ParseFile(f);
            UploadFile(f);
        }

    }


    // output file information
    function ParseFile(file) {

        /*Debug*/
        Output(
            "<p>File information: <strong>" + file.name +
            "</strong> type: <strong>" + file.type +
            "</strong> size: <strong>" + file.size +
            "</strong> bytes</p>"
        );

        // display an image
        if (file.type.indexOf("image") == 0) {
            var reader = new FileReader();
            reader.onload = function(e) {
                Output(
                    "<p>" +
                    //"<strong>" + file.name + ":</strong><br />" +
                    '<img width="130" height="100" src="' + e.target.result + '" />' +
                    '<br />' +
                    '<input type="text" name="photo_name" value="'+ file.name +'" />' +
                    '<br />' +
                    '<input type="text" name="photo_caption" value="Caption" /></p>'
                );
            }
            reader.readAsDataURL(file);
        }

        // display text
        if (file.type.indexOf("text") == 0) {
            var reader = new FileReader();
            reader.onload = function(e) {
                Output(
                    "<p><strong>" + file.name + ":</strong></p><pre>" +
                    e.target.result.replace(/</g, "&lt;").replace(/>/g, "&gt;") +
                    "</pre>"
                );
            }
            reader.readAsText(file);
        }

    }


    // upload JPEG files
    function UploadFile(file) {

        // following line is not necessary: prevents running on SitePoint servers
        if (location.host.indexOf("sitepointstatic") >= 0) return

        var xhr = new XMLHttpRequest();
        if (xhr.upload && (file.type == "image/jpeg" || file.type == "image/png") && file.size <= $id("MAX_FILE_SIZE").value) {

            // create progress bar
            var o = $id("progress");
            var progress = o.appendChild(document.createElement("p"));
            progress.appendChild(document.createTextNode("upload " + file.name));


            // progress bar
            xhr.upload.addEventListener("progress", function(e) {
                var pc = parseInt(100 - (e.loaded / e.total * 100));
                progress.style.backgroundPosition = pc + "% 0";
            }, false);

            // file received/failed
            xhr.onreadystatechange = function(e) {
                if (xhr.readyState == 4) {
                    progress.className = (xhr.status == 200 ? "success" : "failure");
                }
            };

            // start upload
            xhr.open("POST", $id("upload").action, true);
            xhr.setRequestHeader("X_FILENAME", file.name);
            xhr.send(file);

        }

    }


    // initialize
    function Init() {

        var fileselect = $id("fileselect"),
            filedrag = $id("filedrag"),
            submitbutton = $id("submitbutton");

        // file select
        fileselect.addEventListener("change", FileSelectHandler, false);

        // is XHR2 available?
        var xhr = new XMLHttpRequest();
        if (xhr.upload) {

            // file drop
            filedrag.addEventListener("dragover", FileDragHover, false);
            filedrag.addEventListener("dragleave", FileDragHover, false);
            filedrag.addEventListener("drop", FileSelectHandler, false);
            filedrag.style.display = "block";

            // remove submit button
            submitbutton.style.display = "none";
        }

    }

    // call initialization file
    if (window.File && window.FileList && window.FileReader) {
        Init();
    }


})();

先感谢您。

4

2 回答 2

9

你现在可能已经解决了你的问题,但我在这里发布这个解决方案是为了帮助其他遇到同样问题的人。在您的 js 中,有一行内容为

 xhr.setRequestHeader("X_FILENAME", file.name);

但应该阅读

 xhr.setRequestHeader("X-FILENAME", file.name);

since underscores are deprecated in later Apache releases (see also Header names with underscores ignored in php 5.5.1 / apache 2.4.6)

于 2014-06-12T09:58:19.560 回答
0

我在我的一个 Ubuntu WAMP 安装中遇到了这个问题。您的上传 URL(在 Javascript 方面指定的 POST URL)需要是完全限定路径而不是相对路径。但是,我看不到该值,但似乎$id("upload").action是您代码中任何内容的值。如果您有权访问它们,您可以通过查看 apache 日志来确认这是原因。如果您在尝试发送文件时看到 404 错误,那么这就是您的问题。那是假设请求甚至完全命中您的服务器。

于 2012-12-13T03:13:00.090 回答