php为什么不将图像内容写入磁盘

how come php is not writing the image contents to disk?

本文关键字:磁盘 为什么不 图像 php      更新时间:2023-09-26

我有一些代码使用多部分表单和HTML5文件对象将图像(或电影、ppt等)上传到服务器,PHP在那里接收图像并写入磁盘。然而,PHP似乎根本没有写入磁盘。

Javascript:

function uploadFile (file, fileid) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            window["fn"+fileid] = xhr.responseText;
            $("progress"+fileid).innerHTML = "<a href='""+window["fn"+fileid]+"'">"+window["fn"+fileid]+"</a>";
        }
    }
    var a = new Element("div");
    a.id = "progress"+fileid;
    a.setStyle("background-color", "#4682B4");
    a.setStyle("height", "20px");
    a.setStyle("width", "0px");
    $("progress-wrapper").adopt(a);
    xhr.upload.onprogress = function(e, a) {
        var percent = Math.round((e.loaded*150)/e.total);
        var acperct = Math.round(percent/1.5);
        $("progress"+fileid).setStyle("width", percent);
        $("progress"+fileid).innerHTML = file.name+" "+acperct+"%";
    }
    alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNNOPQRSTUVWXYZ1234567890".split("");
    tmp_name = [];
    for (i = 0; i < 6; i++) tmp_name[i] = alpha[Math.floor(Math.random() * alpha.length)];
    xhr.open("POST", "upload.php", true);
    xhr.setRequestHeader("Content-Type", "multipart/form-data");
    xhr.setRequestHeader("size", file.size);
    xhr.setRequestHeader("name", file.name);
    xhr.setRequestHeader("type", file.type);
    xhr.setRequestHeader("tmp_name", ""+tmp_name.join(""));
    xhr.send(file);
}

PHP:

<?
    function apache_request_headers() { 
        foreach($_SERVER as $key=>$value) { 
            if (substr($key,0,5)=="HTTP_") { 
                $key=str_replace(" ","-",ucfirst(strtolower(str_replace("_","_",substr($key,5))))); 
                $out[$key]=$value; 
            }else{ 
                $out[$key]=$value; 
    } 
        } 
        return $out; 
    } 
    $headers = apache_request_headers();
    $contents = file_get_contents("php://input");
    echo $contents;
    $ffilename=$headers["tmp_name"].$headers["name"];
    $all = array('png','jpeg','jpg','gif','mov','txt','wmv','pdf');
    $fh = fopen("upload/".$ffilename, "w+");
    fwrite($fh, $contents);
    fclose($fh);
    echo "upload/".$ffilename;
?>

所发生的情况是,在写入的文件或文本upload/中要么什么都没有。

怎么了?

您没有指定在哪个平台上运行此代码,但如果它是基于unix的,请检查上传目录上的权限-确保为运行apache的所有者/组设置了写入权限。作为一个快速测试,请执行chmod 0777 upload/并查看文件是否显示。

在回显内容之前,设置内容的文件类型的mime类型,例如,如果是jpg:

header("Content-type: image/jpg");
echo $contents;

只是要确保不要重复任何其他内容。如果你看到了图像,那么你就知道它至少正确地到达了服务器。

不管怎样,它并没有像应该的那样将你看到的字符串保存到文件中。正如其他人所说,检查权限。此外,尝试此操作来测试写入尝试(在删除header()调用之后):

$fwrite = fwrite($fh, $contents);
if ($fwrite === false) {
    echo 'write failed';
}
else {
    echo "wrote $fwrite bytes";
}