Доработка скрипта загрузки Ajax

(Ответов: 13, Просмотров: 2242)
Страница 1 из 2 12 Последняя
  1. [web-developer] Аватар для cOAPerator
    • Регистрация: 22.02.2011
    • Сообщений: 615
    • Репутация: 111
    • Webmoney BL: ?
    Значится есть вот такой класс:

    класс

    PHP код:
    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($temp0SEEK_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.');
            }      
        }   

    [свернуть]

    форма загрузчика на ajax

    PHP код:
    <!DOCTYPE html>
    <
    html>
      <
    head>
        <
    meta charset="utf-8">
        <
    title>Fine Uploader Demo</title>
        <
    link href="client/fileuploader.css" rel="stylesheet">
      </
    head>
      <
    body>
        <
    div id="fine-uploader"></div>
        <
    script src="client/fileuploader.js"></script>
        <script>
          function createUploader() {
            var uploader = new qq.FileUploader({
              element: document.getElementById('fine-uploader'),
              // Use the relevant server script url here
              action: 'yourserverscript.php'
            });
          }
        
          window.onload = createUploader;
        </script>

        </body>
    </html> 
    [свернуть]

    но так как я в ООП ни гугу, прошу помощи у Вас, людей компетентных..
    не могу понять как принять загружаемый файл с Ajax загрузчика.
    • 0
  2. Гуру Аватар для akrustam
    • Регистрация: 21.05.2010
    • Сообщений: 1,161
    • Репутация: 285
    • Webmoney BL: ?
    Можно еще выложить сам JS. Как его он отправляет.
    • 0
  3. [web-developer] Аватар для cOAPerator
    • Регистрация: 22.02.2011
    • Сообщений: 615
    • Репутация: 111
    • Webmoney BL: ?
    akrustam, да, можно, тока это плагин на JS. вот 2.1.2.zip
    • 0
  4. [web-developer] Аватар для cOAPerator
    • Регистрация: 22.02.2011
    • Сообщений: 615
    • Репутация: 111
    • Webmoney BL: ?
    если быть точным, то это вот этот плагин _http://fineuploader.com/fine-uploader-demo.html
    • 0
  5. Гуру Аватар для akrustam
    • Регистрация: 21.05.2010
    • Сообщений: 1,161
    • Репутация: 285
    • Webmoney BL: ?
    ПРивет. Вчера не успел. Щас гляну.

    ---------- Сообщение добавлено 12:55 ---------- Предыдущее 12:02 ----------

    Смотри как должно работать.

    PHP код:
    <?

    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("uploads/".$path"w");        
            
    fseek($temp0SEEK_SET);
            
    stream_copy_to_stream($temp$target);
            
    fclose($target);
            
    echo 
    "{success:true}";
            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.');
            }      
        }   
    }
    $OBJ = new qqUploadedFileXhr;

    $OBJ->save($OBJ->getName());

    ?>
    Конечно скрипт плохой. Нету проверок расширений файлов, размера, и загружался уже он.
    • 0
  6. [web-developer] Аватар для cOAPerator
    • Регистрация: 22.02.2011
    • Сообщений: 615
    • Репутация: 111
    • Webmoney BL: ?
    akrustam, чето я не понял, в чем разница между верхним и нижним вариатом. Как мне файл то принять, чтобы перемеслить в нужную папку то? с какой переменной?
    Этот код, как в ридми написано - это шаблон принятия файлов.. все проверки надо вручную добавлять.. то есть как я понял этот скрипт - связующее звено между скриптом загрузки на ajax и моим скриптом загрузки файла в нужный мне каталог.
    так вот, С какой переменной файл приходит? например в обычной форме ты отправляешь форму с файлом. Файл придет в $_GET['имя_файла'] а тут в какой?
    • 0
  7. Гуру Аватар для akrustam
    • Регистрация: 21.05.2010
    • Сообщений: 1,161
    • Репутация: 285
    • Webmoney BL: ?
    Скрипт ajax использует подход выгрузки данных через поток "php://input". Сам скрипт передает через $_GET['qqfile'] название файла (функция getName() ). Вот здесь
    PHP код:
    $OBJ = new qqUploadedFileXhr;
    $OBJ->save($OBJ->getName()); 
    Мы запускаем систему приема файла.

    Тут идет сохранение в файл данных их потока.
    PHP код:
    $target fopen("uploads/".$path"w");        
            
    fseek($temp0SEEK_SET);
            
    stream_copy_to_stream($temp$target); 
    Вот тут "fopen("uploads/".$path, "w")" пишется папка для закачки и названием файла.

    В принципе все.
    Все просто.
    • 1

    Спасибо сказали:

    cOAPerator(03.11.2012),
  8. [web-developer] Аватар для cOAPerator
    • Регистрация: 22.02.2011
    • Сообщений: 615
    • Репутация: 111
    • Webmoney BL: ?
    Чет нифига не работает( все равно ответ filed кажет

    а файл закачивается кстати, значит где то еще ответ отправляется обратно верно?

    полный код скрипта

    PHP код:
    <?php

    /****************************************
    Example of how to use this uploader class...
    You can uncomment the following lines (minus the require) to use these as your defaults.

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

    require('valums-file-uploader/server/php.php');
    $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);

    // Call handleUpload() with the name of the folder, relative to PHP's getcwd()
    $result = $uploader->handleUpload('uploads/');

    // to pass data through iframe you will need to encode all html tags
    echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);

    /******************************************/



    /**
     * 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('uploads/'.$path"w");        
            
    fseek($temp0SEEK_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.');
            }      
        }   
    }
    // это я добавил
    $OBJ = new qqUploadedFileXhr;
    $OBJ->save($OBJ->getName()); 

    /**
     * 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 10485760;
        private 
    $file;
        private 
    $uploadName;

        function 
    __construct(array $allowedExtensions = array(), $sizeLimit 10485760){        
            
    $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
            }
        }
        
        public function 
    getUploadName(){
            if( isset( 
    $this->uploadName ) )
                return 
    $this->uploadName;
        }

        public function 
    getName(){
            if (
    $this->file)
                return 
    $this->file->getName();
        }
        
        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){
            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 $pathinfo['filename'];
            
    //$filename = md5(uniqid());
            
    $ext = @$pathinfo['extension'];        // hide notices if extension is empty

            
    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 '.');
            }
            
            
    $ext = ($ext == '') ? $ext '.' $ext;
            
            if(!
    $replaceOldFile){
                
    /// don't overwrite previous files that were uploaded
                
    while (file_exists($uploadDirectory $filename $ext)) {
                    
    $filename .= rand(1099);
                }
            }
            
            
    $this->uploadName $filename $ext;

            if (
    $this->file->save($uploadDirectory $filename $ext)){
                return array(
    'success'=>true);
            } else {
                return array(
    'error'=> 'Could not save uploaded file.' .
                    
    'The upload was cancelled, or server error encountered');
            }
            
        }    
    }
    ?>
    [свернуть]
    Последний раз редактировалось cOAPerator; 03.11.2012 в 03:43.
    • 0
  9. Гуру Аватар для akrustam
    • Регистрация: 21.05.2010
    • Сообщений: 1,161
    • Репутация: 285
    • Webmoney BL: ?
    Я тебе готовый скрипт дал. В их скрипте идет обработка 2 типов обычная загрузка файла и через ajax. Я выделил только ajax. У меня работает. В js вместо action: 'yourserverscript.php' поставить свой файл.
    • 0
  10. [web-developer] Аватар для cOAPerator
    • Регистрация: 22.02.2011
    • Сообщений: 615
    • Репутация: 111
    • Webmoney BL: ?
    akrustam, да я понял. я создал файл yourserverscript.php и в него запихнул то что ты мне написал. в итоге файл загружается куда мне надо, но ответ пишет Upload failed
    вот скрин:Нажмите на изображение для увеличения.  Название:	2012-11-03_152218.png  Просмотров:	6  Размер:	2.4 Кб  ID:	6657
    • 0
Страница 1 из 2 12 Последняя

Похожие темы

Темы Раздел Ответов Последний пост
Доработка шаблона Speechless
WordPress 6 06.10.2012 11:30
Доработка сайта на joomla
Создание сайтов 8 05.04.2012 01:09
Доработка сайта на Joomla
Создание сайтов 2 30.12.2011 05:42
Доработка шаблона на Wordpress
Создание сайтов 1 26.11.2011 15:09

У кого попросить инвайт?

Вы можете попросить инвайт у любого модератора:

Информеры