0

私は一日の大半をこの問題の解決策を探しましたが、まだ暗闇の中にいます。私のクライアントのために、画像をアップロードするためのシンプルな Web ギャラリーを作成し、valums file uploaderを使用しています。しばらく前に解決した設定ミスを除いて、私が作成した他のサイトではこれまで何の問題もありませんでした。

それで、問題は何ですか?

ファイルサイズが 260KB 未満の画像をアップロードすると、正常に動作します。しかし、より大きな画像をアップロードすると、エラーは返されません。画像がアップロードされていないため、空のサムネイルが表示されます。

Chrome コンソールを開くと、次のように表示されます。

POST http://designflowstudio.com/gallery2/include/upload.php?url=uploads%2Fe558c4dfc2a0f0d60f5ebff474c97ffc&fid=7&qqfile=316267269718409738080100.jpg 403 (Forbidden) fileuploader.js:1463
POST http://designflowstudio.com/gallery2/include/upload.php?url=uploads%2Fe558c4dfc2a0f0d60f5ebff474c97ffc&fid=7&qqfile=3.jpg 403 (Forbidden) fileuploader.js:1463

場合によっては、「要求エンティティが大きすぎます」という 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;

そして、これがサーバーがファイルを処理するための私のPHPです:

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

繰り返しますが、MySQL へのすべての呼び出し、require() を含むファイルは有効です。スクリプトは他の 2 つのサーバーでは機能しますが、このサーバーでは機能しません。

お時間をいただきありがとうございます。

4

1 に答える 1

0

content-type ヘッダーが原因でサーバーが停止している場合は、サーバーに構成上の問題があります。この混乱したサーバーを回避するには、この行をコメント アウトする代わりに、forceMultipart オプションを true に設定してみてください。ただし、サーバーがマルチパート エンコードされたリクエストを正しく処理できると仮定します。これはすべて、2.1-SNAPSHOT バージョンのアップローダーを使用していることを前提としています。これは、私が言及したオプションがこのバージョンで最初に登場したためです。

于 2012-10-10T13:51:20.957 に答える