Jump to content
Fórum Script Brasil
  • 0

Ajuda com script de Upload


Alessandro Fazolo

Question

Boa noite pessoal! Estou trabalhando na adaptação de um script em PHP para ASP e como não entendo muito de PHP precisaria da ajuda para que comentassem algumas funções para que eu possa cria-las no meu script ASP. O script é de upload de imagem do NicEdit e tem uma rotina que retorna uma barra de progresso. A parte de upload eu já fiz mas a parte que retorna o barra de progresso ainda não conseguir adaptar. Creio que a chave do mistério esteja em algumas passagem que não consegui entender e que estão marcada abaixo em vermelho. Quem puder dizer pra mim o que elas fazer eu agradeço. Segue o código inteiro para melhor compreensão:

<?php

define('NICUPLOAD_PATH', './blog/images'); 
                                      
define('NICUPLOAD_URI', '/blog/images');   

$nicupload_allowed_extensions = array('jpg','jpeg','png','gif','bmp');

[color="#FF0000"]$rfc1867 = function_exists('apc_fetch') && ini_get('apc.rfc1867');[/color]

if(!function_exists('json_encode')) {
    die('{"error" : "Image upload host does not have the required dependicies (json_encode/decode)"}');
}

$id = $_POST['APC_UPLOAD_PROGRESS'];
if(empty($id)) {
    $id = $_GET['id'];
}

if($_SERVER['REQUEST_METHOD']=='POST') { // Upload is complete
    if(empty($id) || !is_numeric($id)) {
        nicupload_error('ID do Upload inválido');
    }
    if(!is_dir(NICUPLOAD_PATH) || !is_writable(NICUPLOAD_PATH)) {
        nicupload_error('Upload directory '.NICUPLOAD_PATH.' must exist and have write permissions on the server');
    }
    
    $file = $_FILES['nicImage'];
    $image = $file['tmp_name'];
    
    $max_upload_size = ini_max_upload_size();
    if(!$file) {
        nicupload_error('Must be less than '.bytes_to_readable($max_upload_size));
    }
    
    $ext = strtolower(substr(strrchr($file['name'], '.'), 1));
    @$size = getimagesize($image);
    if(!$size || !in_array($ext, $nicupload_allowed_extensions)) {
        nicupload_error('Invalid image file, must be a valid image less than '.bytes_to_readable($max_upload_size));
    }
    
    [color="#ff0000"]$filename = $id.'.'.$ext;[/color]
[color="#ff0000"]    $path = NICUPLOAD_PATH.'/'.$filename;[/color]
    
   [color="#ff0000"] if(!move_uploaded_file($image, $path)) {[/color]
        nicupload_error('Server error, failed to move file');
    }
    
   [color="#ff0000"] if($rfc1867) {[/color]
[color="#ff0000"]        $status = apc_fetch('upload_'.$id);[/color]
    }
   [color="#ff0000"] if(!$status) {[/color]
[color="#ff0000"]        $status = array();[/color]
    }
    $status['done'] = 1;
    $status['width'] = $size[0];
    $status['url'] = nicupload_file_uri($filename);
    
   [color="#ff0000"] if($rfc1867) {[/color]
[color="#ff0000"]        apc_store('upload_'.$id, $status);[/color]
[color="#ff0000"]    }[/color]

    nicupload_output($status, $rfc1867);
    exit;
} else [color="#ff0000"]if(isset($_GET['check'])) { // Upload progress check[/color]
[color="#ff0000"]    $check = $_GET['check'];[/color]
[color="#ff0000"]    if(!is_numeric($check)) {[/color]
[color="#ff0000"]        nicupload_error('Invalid upload progress id');[/color]
    }
    
   [color="#ff0000"] if($rfc1867) {[/color]
[color="#ff0000"]        $status = apc_fetch('upload_'.$check);[/color]
        
        if($status['total'] > 500000 && $status['current']/$status['total'] < 0.9 ) { // Large file and we are < 90% complete
                $status['interval'] = 3000;
        } else if($status['total'] > 200000 && $status['current']/$status['total'] < 0.8 ) { // Is this a largeish file and we are < 80% complete
                $status['interval'] = 2000;
        } else {
                $status['interval'] = 1000;
        }
        
        nicupload_output($status);
    } else {
        $status = array();
        $status['noprogress'] = true;
        foreach($nicupload_allowed_extensions as $e) {
           [color="#ff0000"] if(file_exists(NICUPLOAD_PATH.'/'.$check.'.'.$e)) {[/color]
[color="#ff0000"]                $ext = $e;[/color]
[color="#ff0000"]                break;[/color]
            }
        }
        if($ext) {
            $status['url'] = nicupload_file_uri($check.'.'.$ext);
        }
        nicupload_output($status);
    }
}


// UTILITY FUNCTIONS

function nicupload_error($msg) {
    echo [color="#ff0000"]nicupload_output(array('error' => $msg)); [/color]
}

function nicupload_output($status, $showLoadingMsg = false) {
    $script = '
        try {
            '.(($_SERVER['REQUEST_METHOD']=='POST') ? 'top.' : '').'nicUploadButton.statusCb('.json_encode($status).');
        } catch(e) { alert(e.message); }
    ';
    
    if($_SERVER['REQUEST_METHOD']=='POST') {
        echo '&lt;script>'.$script.'</script>';
    } else {
        echo $script;
    }
    
    if($_SERVER['REQUEST_METHOD']=='POST' && $showLoadingMsg) {      

echo <<<END
    <html><body>
        <div id="uploadingMessage" style="text-align: center; font-size: 14px;">
            <img src="http://www.alessandrofazolo.com/js/rte/ajax-loader.gif" style="float: right; margin-right: 40px;" />
            <strong>Carregando...</strong> Aguarde!
        </div>
    </body></html>
END;

    }
    
    exit;
}

function nicupload_file_uri($filename) {
    return NICUPLOAD_URI.'/'.$filename;
}

function ini_max_upload_size() {
    $post_size = ini_get('post_max_size');
    $upload_size = ini_get('upload_max_filesize');
    if(!$post_size) $post_size = '8M';
    if(!$upload_size) $upload_size = '2M';
    
    return min( ini_bytes_from_string($post_size), ini_bytes_from_string($upload_size) );
}

function ini_bytes_from_string($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $val;
}

function bytes_to_readable( $bytes ) {
    if ($bytes<=0)
        return '0 Byte';
   
    $convention=1000; //[1000->10^x|1024->2^x]
    $s=array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB');
    $e=floor(log($bytes,$convention));
    return round($bytes/pow($convention,$e),2).' '.$s[$e];
}

?

>

Link to comment
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152.2k
    • Total Posts
      652.1k
×
×
  • Create New...