$ _SERVER [“CONTENT_LENGTH”]在使用XmlHttpRequest上传文件时返回零

时间:2010-09-08 03:45:41

标签: php jquery xmlhttprequest

我在我的开发机器上遇到了一个问题,这台机器看起来很孤立,我无法弄明白。 我有一个jQuery文件上传器,它将用户选择的文件发布到PHP脚本,以便使用XmlHttpRequest进行处理。该脚本在运行带有MAMP 1.9的OSX10.6.3的MacBook Pro上工作正常,但是在我的iMac上使用完全相同的操作系统和MAMP版本,并且具有相同的服务器映像,它会失败。

我已将错误原因追溯到属性$_SERVER["CONTENT_LENGTH"]返回 0,即使我可以正确获取文件名,其他所有内容似乎都已成功完成请求。出于某种原因,它似乎不会给我实际的内容长度。以下是导致问题的代码 - 有问题的函数是getSize()

class qqUploadedFileXhr {
    /**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
    function save($path) {    
        $input = fopen("php://input", "r");
        $temp = tmpfile();
        $realSize = stream_copy_to_stream($input, $temp);
        fclose($input);

        if ($realSize != $this->getSize()){            
            return false;
        }

        $target = fopen($path, "w");        
        fseek($temp, 0, SEEK_SET);
        stream_copy_to_stream($temp, $target);
        fclose($target);

        return true;
    }
    function getName() {
        return $_GET['qqfile'];
    }
    function getSize() {
        if (isset($_SERVER["CONTENT_LENGTH"])){
            return (int)$_SERVER["CONTENT_LENGTH"]; //*THIS* is returning 0            
        } else {
            throw new Exception('Getting content length is not supported.');
        }      
    }   
}

5 个答案:

答案 0 :(得分:6)

解决了!似乎我使用的jQuery脚本在firefox 3.5.x下失败,我更新到3.6.9并且它工作正常。

现在我必须找到一些方法使它向后兼容旧版本的firefox。

答案 1 :(得分:3)

您是否将编码类型设置为multipart/form-data

<form action="upload.php" method="post" enctype="multipart/form-data">
  ...
  <input type="file" ... />
  ...
</form>

答案 2 :(得分:3)

可能正在使用分块编码,这不会发送内容长度。

答案 3 :(得分:0)

我使用相同的插件,即使使用旧版浏览器,最新版本似乎也能正常运行。我仍然有IE6和IE7的一些显示/渲染问题,但我通过使按钮不透明并添加图像来覆盖它来解决这些问题。我还修改了接收PHP脚本只是一个函数而不是多个函数。并不适合所有场合,但它适用于所有浏览器:

public function web_upload_file_ajax(){
    $return             = array();
    $uploaded_file      = array('name'=>'', 'size'=>0);
    // list of valid extensions, ex. array("jpeg", "xml", "bmp")
    $allowedExtensions  = array('jpg', 'jpeg', 'png', 'gif', 'bmp','txt','csv');
    // max file size in bytes
    $sizeLimit          = 3 * 1024 * 1024;
    //folder to upload the file to - add slash at end
    $uploadDirectory    = TMPPATH.'tmp_upload'.DIRECTORY_SEPARATOR;
    if(!is_dir($uploadDirectory)){
        @mkdir($uploadDirectory, 0766, true);
    }
    if(!is_dir($uploadDirectory)){
        $return         = array('error' => 'Server error. Impossible to create the cache folder:'.$uploadDirectory);
    }elseif(!is_writable($uploadDirectory)){
        $return         = array('error' => 'Server error. Upload directory is not writable.');
    } else {
        $postSize           = $this->bytes_to_num(ini_get('post_max_size'));
        $uploadSize         = $this->bytes_to_num(ini_get('upload_max_filesize'));

        if ($postSize < $sizeLimit || $uploadSize < $sizeLimit){
            $size = max(1, $sizeLimit / 1024 / 1024) . 'M';
            $return = array('error' => 'increase post_max_size and upload_max_filesize to '.$size);
        }elseif (isset($_GET['qqfile'])) {
            $uploaded_file['name']  = $_GET['qqfile'];
            if (isset($_SERVER['CONTENT_LENGTH'])){
                $uploaded_file['size']  = (int)$_SERVER['CONTENT_LENGTH'];
            } else {
                $return = array('error'=>'Getting content length is not supported.');
            }
        } elseif (isset($_FILES['qqfile'])) {
            $uploaded_file['name']  = $_FILES['qqfile']['name'];
            $uploaded_file['size']  = $_FILES['qqfile']['size'];
        } else {
            $return = array('error' => 'No files were uploaded.');
        }
        if(count($return)==0){
            if($uploaded_file['size'] == 0)                         $return = array('error' => 'File is empty');
            elseif($uploaded_file['size'] > $sizeLimit)             $return = array('error' => 'File is too large');
            elseif($uploaded_file['name']!=''){
                $pathinfo   = pathinfo($uploaded_file['name']);
                $filename   = $pathinfo['filename'];
                $ext        = $pathinfo['extension'];
                if($allowedExtensions && !in_array(strtolower($ext), $allowedExtensions)){
                    $return = array('error' => 'File has an invalid extension, it should be one of '.implode(', ', $allowedExtensions).'.');
                }
            }
        }
        if(count($return)==0){
            // overwrite previous files that were uploaded
            $filename = ll('sessions')->get_id();

            // don't overwrite previous files that were uploaded
            while (file_exists($uploadDirectory.$filename.'.'.$ext)) {
                $filename .= rand(10, 99);
            }

            $saved  = false;
            $path   = $uploadDirectory.$filename.'.'.$ext;
            if (isset($_GET['qqfile'])) {
                $input      = fopen('php://input', 'r');
                $temp       = tmpfile();
                $realSize   = stream_copy_to_stream($input, $temp);
                fclose($input);

                if ($realSize != $uploaded_file['size']){
                    $saved = false;
                } else {
                    $target = fopen($path, 'w');
                    fseek($temp, 0, SEEK_SET);
                    stream_copy_to_stream($temp, $target);
                    fclose($target);
                    $saved = true;
                }
            } else {
                if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){
                    $saved = false;
                }
                $saved = true;
            }
            if ($saved){
                $return = array('success'=>true, 'file'=>$filename.'.'.$ext);
            } else {
                $return = array('error'=> 'Could not save uploaded file. The upload was cancelled, or server error encountered');
            }
        }
    }
    // to pass data through iframe you will need to encode all html tags
    echo htmlspecialchars(json_encode($return), ENT_NOQUOTES);
}

这里是我用作辅助函数的bytes_to_num,但如果你愿意,也可以将它包含在同一个函数中:

/**
 * This function transforms bytes (like in the the php.ini notation) for numbers (like '2M') to an integer (2*1024*1024 in this case)
 */
public function bytes_to_num($bytes){
    $bytes  = trim($bytes);
    $ret    = $bytes+0;
    if($ret==0 || strlen($ret)>=strlen($bytes)){
        return $ret;
    }
    $type   = substr($bytes, strlen($ret));
    switch(strtoupper($type)){
        case 'P':
        case 'Pb':
            $ret *= 1024;
        case 'T':
        case 'Tb':
            $ret *= 1024;
        case 'G':
        case 'Gb':
            $ret *= 1024;
        case 'M':
        case 'Mb':
            $ret *= 1024;
        case 'K':
        case 'Kb':
            $ret *= 1024;
            break;
    }
    return $ret;
}

答案 4 :(得分:0)

$headers = apache_request_headers();
echo $headers['Content-Length'];

我会假设这个也会返回0?