Php ValumsAjax在xhr.send(文件)之后上传损坏的脚本-有时有效,有时无效

Php ValumsAjax在xhr.send(文件)之后上传损坏的脚本-有时有效,有时无效,php,jquery,fine-uploader,valums-file-uploader,Php,Jquery,Fine Uploader,Valums File Uploader,我在一天中的大部分时间里都在寻找解决办法,但我仍然一无所知。我为我的一个客户创建了一个简单的网络图库,用于上传图像,我正在使用它。到目前为止,我在我创建的任何其他网站上都没有遇到任何问题,除了我不久前解决的配置错误 那么,问题是什么 当我上传一个文件大小低于260KB的图像时,它工作正常。但是,当我上传一张更大的图片时,它不会让我返回任何错误。我只是得到一个空的缩略图,因为图像没有上传 当我打开Chrome控制台时,我看到的是: 在某些情况下,我得到413错误“请求实体太大” 让我说,这个问题确

我在一天中的大部分时间里都在寻找解决办法,但我仍然一无所知。我为我的一个客户创建了一个简单的网络图库,用于上传图像,我正在使用它。到目前为止,我在我创建的任何其他网站上都没有遇到任何问题,除了我不久前解决的配置错误

那么,问题是什么

当我上传一个文件大小低于260KB的图像时,它工作正常。但是,当我上传一张更大的图片时,它不会让我返回任何错误。我只是得到一个空的缩略图,因为图像没有上传

当我打开Chrome控制台时,我看到的是:

在某些情况下,我得到413错误“请求实体太大”

让我说,这个问题确实让我恼火,因为该脚本在本地web服务器(apache)和web服务器上运行良好。在这里,我可以上传尽可能多的图片,但在客户端的web服务器上

如果有人有时间和意愿帮助我,下面是我用来调用valums上传程序的JavaScript:

     function createUploader(){
 var uploader = new qq.FileUploaderBasic({
  debug: true,
  multiple: true,
  allowedExtensions: [<?php $tmp=".";foreach($allowedExt as $ext){$tmp.="'$ext', ";}echo substr($tmp,1,strlen($tmp)-3);?>],
  button: document.getElementById('uploadDiv'),
  action: '<?php echo$home;?>include/upload.php',
  sizeLimit: <?php echo$sizeLimit;?>,
  forceMultipart: true,
  params: {'url':'uploads/<?php echo$g['path'];?>','fid':'<?php echo$g['id'];?>'},
  onSubmit: function(id, fName){$('#upload-list').append('<div id="upload-list-'+id+'" class="gallery" rel="'+fName+'"><div class="progress'+id+'"></div>');$('.progress'+id).progressbar({value:0})},
  onProgress: function(id, fName, loaded, total){
   var p = 0;
   p = parseFloat(loaded/total*100);
   if(isNaN(p)) p = '';
   $('.progress'+id).progressbar("option","value",p);
  },
  onComplete: function(id,fName,json){
   if(json.error){
    $('#upload-list-'+id).html(fName+'<br />'+json.error);
   }else{
    $('#upload-list-'+id)
     .attr("rel",json.fname)
     .html('<img class="cmd" id="deleteImg" rel="'+json.id+'" src="<?php echo$home;?>images/delete.png" title="Delete picture" /><img class="img" src="<?php echo$home;?>uploads/<?php echo$g['path'];?>/th_'+json.fname+'" /><input class="ut" type="text" name="name" value="'+json.name+'" /><input class="ud" type="text" name="desc" /><div class="cl"></div>')
     .attr("id",json.id);
   }
  },
  onError: function(id,fName,error){
   console.log(id+' '+fName+' '+error);
  }
 });
}
window.onload = createUploader;
函数createUploader(){
var uploader=new qq.fileuploader基本({
是的,
多重:对,

允许的扩展:[如果服务器因内容类型标题而阻塞,则服务器上会出现一些配置问题。要解决这一混乱的服务器问题,您可能应该尝试将forceMultipart选项设置为true,前提是您的服务器可以正确处理多部分编码的请求。这一切都假设您正在使用2.1快照版本的上传者,作为我提到的选项首先出现在这个版本。

嗯,我想出来了。脚本FILULPROADADR.JS将内容类型设置为Apple /Octt流。到目前为止,所有服务器都很好,但不是这个。当我评论它设置内容类型的那一部分时,它开始工作了。我的评论是:
xhr.setRequestHeader(“内容类型”、“应用程序/八位字节流”);
同时,我认为服务器上启用了mod_安全并破坏了POST数据。我发布此消息是希望有一天有人可能需要此信息。因为我经常在SO搜索帮助。干杯:)我正在使用选项forceMultipart:true,它没有改变任何东西。起初我使用旧版本,然后更新到最新版本。错误仍然存在。在一些研究和谷歌搜索之后,我仍然怀疑mod_安全性存在问题,但客户不愿意联系他的管理员来澄清这一点并解决问题更改服务器设置。此外,uploader可用于Chrome、Opera和IE,但不能用于Firefox。某些内容将内容类型设置为“application/octet stream”,当然,它被拒绝。还尝试了内容类型“multipart/form data”,不走运。XHR POST请求的内容类型在uploader js代码中硬编码为application/octet stream。如果将forceMultipart设置为true不能解决您的问题,那么问题不在于内容类型。我的意思是,在FireFox中,XHR contentType设置为“application/octet stream”在我在uploader js中评论了这一行之后,在其他浏览器中没有发送contentType,上传工作正常。我可以告诉客户端这是服务器配置错误吗?我肯定会说问题是服务器端的。
     function createUploader(){
 var uploader = new qq.FileUploaderBasic({
  debug: true,
  multiple: true,
  allowedExtensions: [<?php $tmp=".";foreach($allowedExt as $ext){$tmp.="'$ext', ";}echo substr($tmp,1,strlen($tmp)-3);?>],
  button: document.getElementById('uploadDiv'),
  action: '<?php echo$home;?>include/upload.php',
  sizeLimit: <?php echo$sizeLimit;?>,
  forceMultipart: true,
  params: {'url':'uploads/<?php echo$g['path'];?>','fid':'<?php echo$g['id'];?>'},
  onSubmit: function(id, fName){$('#upload-list').append('<div id="upload-list-'+id+'" class="gallery" rel="'+fName+'"><div class="progress'+id+'"></div>');$('.progress'+id).progressbar({value:0})},
  onProgress: function(id, fName, loaded, total){
   var p = 0;
   p = parseFloat(loaded/total*100);
   if(isNaN(p)) p = '';
   $('.progress'+id).progressbar("option","value",p);
  },
  onComplete: function(id,fName,json){
   if(json.error){
    $('#upload-list-'+id).html(fName+'<br />'+json.error);
   }else{
    $('#upload-list-'+id)
     .attr("rel",json.fname)
     .html('<img class="cmd" id="deleteImg" rel="'+json.id+'" src="<?php echo$home;?>images/delete.png" title="Delete picture" /><img class="img" src="<?php echo$home;?>uploads/<?php echo$g['path'];?>/th_'+json.fname+'" /><input class="ut" type="text" name="name" value="'+json.name+'" /><input class="ud" type="text" name="desc" /><div class="cl"></div>')
     .attr("id",json.id);
   }
  },
  onError: function(id,fName,error){
   console.log(id+' '+fName+' '+error);
  }
 });
}
window.onload = createUploader;
require("config.php");
require("SimpleImage.php");
ini_set("log_errors" , "1");
ini_set("error_log" , "php-errors-upload.log");
ini_set("display_errors" , "1");
/**
 * Handle file uploads via XMLHttpRequest
 */
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"];            
        } else {
            throw new Exception('Getting content length is not supported.');
        }
    }   
}

/**
 * Handle file uploads via regular form post (uses the $_FILES array)
 */
class qqUploadedFileForm {
    /**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
    function save($path) {
        if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){
            return false;
        }
        return true;
    }
    function getName() {
        return $_FILES['qqfile']['name'];
    }
    function getSize() {
        return $_FILES['qqfile']['size'];
    }
}

class qqFileUploader {
    private $allowedExtensions = array();
    private $sizeLimit = 20485760;
    private $file;

    function __construct(array $allowedExtensions = array(), $sizeLimit = 20485760){
        $allowedExtensions = array_map("strtolower", $allowedExtensions);

        $this->allowedExtensions = $allowedExtensions;        
        $this->sizeLimit = $sizeLimit;

        $this->checkServerSettings();

        if (isset($_GET['qqfile'])) {
            $this->file = new qqUploadedFileXhr();
        } elseif (isset($_FILES['qqfile'])) {
            $this->file = new qqUploadedFileForm();
        } else {
            $this->file = false;
        }
    }

    private function checkServerSettings(){        
        $postSize = $this->toBytes(ini_get('post_max_size'));
        $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));

        if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
            $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';             
            die("{'error':'increase post_max_size and upload_max_filesize to $size'}");    
        }        
    }

    private function toBytes($str){
        $val = trim($str);
        $last = strtolower($str[strlen($str)-1]);
        switch($last) {
            case 'g': $val *= 1024;
            case 'm': $val *= 1024;
            case 'k': $val *= 1024;        
        }
        return $val;
    }

    /**
     * Returns array('success'=>true) or array('error'=>'error message')
     */
    function handleUpload($uploadDirectory, $replaceOldFile = FALSE){
        chdir("../");
        if(!file_exists($uploadDirectory)){
          foreach(explode("/",$uploadDirectory) as $val){
            if(empty($val2)){$val2=$val."/";}else{$val2.=$val."/";}
            if($val<>""){if(!file_exists($val2)){mkdir($val2);}}
          }
        }

        if (!is_writable($uploadDirectory)){
            return array('error' => "Server error. Upload directory isn't writable.");
        }

        if (!$this->file){
            return array('error' => 'No files were uploaded.');
        }

        $size = $this->file->getSize();

        if ($size == 0) {
            return array('error' => 'File is empty');
        }

        if ($size > $this->sizeLimit) {
            return array('error' => 'File is too large');
        }

        $pathinfo = pathinfo($this->file->getName());
        $filename = md5($pathinfo['filename'].mt_rand());
        //$filename = md5(uniqid());
        $ext = strtolower($pathinfo['extension']);

        if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
            $these = implode(', ', $this->allowedExtensions);
            return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
        }

        if(!$replaceOldFile){
            /// don't overwrite previous files that were uploaded
            while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
                $filename .= rand(10, 99);
            }
        }
        if ($this->file->save($uploadDirectory .'/'. $filename . '.' . $ext)){
            global $sql_images;
            $md=md5($filename);
            $tmp=mysql_query("SELECT `order` FROM `$sql_images` WHERE `gid`='{$_REQUEST['fid']}' ORDER BY `order` DESC");
            if($tmp&&mysql_num_rows($tmp)>0){$i=mysql_result($tmp,0);$i++;}else{$i=0;}
            mysql_query("INSERT INTO `$sql_images` (`order`,`gid`,`name`,`path`) VALUES ('$i','{$_REQUEST['fid']}','{$pathinfo['filename']}','$filename.$ext')");
            $image = new SimpleImage();
            $image->load($uploadDirectory.'/'.$filename.'.'.$ext);
            $image->resizeToWidth(150);
            $image->save($uploadDirectory.'/th_'.$filename.'.'.$ext);
            return array('success'=>true,'fname'=>$filename.".".$ext,'name'=>$pathinfo['filename'],'id'=>mysql_insert_id());
        } else {
            return array('error'=> 'Could not save uploaded file.' .
                'The upload was cancelled, or server error encountered');
        }
    }
}

// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array();
// max file size in bytes
$sizeLimit = 20*1024*1024;

$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload($_REQUEST['url']);
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);