Maison > php教程 > PHP源码 > le corps du texte

PHP+Ajax图片上传并且无刷新生成缩略图预览

WBOY
Libérer: 2016-06-08 17:20:06
original
1003 Les gens l'ont consulté

图片上传我们介绍过的教程非常的多了,今天我整理的这篇ajax图片上传主要有一个上传之后自动生成小图的功能并且还返回预览效果,下面我们来看看这段代码。

<script>ec(2);</script>


XML/HTML Code

 <div id="upload-wrapper">  <div align="center">    <form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">  <input name="ImageFile" id="imageInput" type="file" />  <input type="submit"  id="submit-btn" value="Upload" />  <img src="images/ajax-loader.gif" id="loading-img"   style="max-width:90%" alt="Please Wait"/>  </form>  <div id="output"></div>  </div>  
</div>
Copier après la connexion



JavaScript Code

<script type="text/javascript">  
$(document).ready(function() {   
    var options = {   
            target:   &#39;#output&#39;,   // target element(s) to be updated with server response   
            beforeSubmit:  beforeSubmit,  // pre-submit callback   
            success:       afterSuccess,  // post-submit callback   
            resetForm: true        // reset the form after successful submit   
        };   
          
     $(&#39;#MyUploadForm&#39;).submit(function() {   
            $(this).ajaxSubmit(options);              
            // always return false to prevent standard browser submit and page navigation   
            return false;   
        });   
});   
  
function afterSuccess()  
{  
    $(&#39;#submit-btn&#39;).show(); //hide submit button  
    $(&#39;#loading-img&#39;).hide(); //hide submit button  
  
}  
  
//function to check file size before uploading.  
function beforeSubmit(){  
    //check whether browser fully supports all File API  
   if (window.File && window.FileReader && window.FileList && window.Blob)  
    {  
          
        if( !$(&#39;#imageInput&#39;).val()) //check empty input filed  
        {  
            $("#output").html("Are you kidding me?");  
            return false  
        }  
          
        var fsize = $(&#39;#imageInput&#39;)[0].files[0].size; //get file size  
        var ftype = $(&#39;#imageInput&#39;)[0].files[0].type; // get file type  
          
  
        //allow only valid image file types   
        switch(ftype)  
        {  
            case &#39;image/png&#39;: case &#39;image/gif&#39;: case &#39;image/jpeg&#39;: case &#39;image/pjpeg&#39;:  
                break;  
            default:  
                $("#output").html("<b>"+ftype+"</b> Unsupported file type!");  
                return false  
        }  
          
        //Allowed file size is less than 1 MB (1048576)  
        if(fsize>1048576)   
        {  
            $("#output").html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.");  
            return false  
        }  
                  
        $(&#39;#submit-btn&#39;).hide(); //hide submit button  
        $(&#39;#loading-img&#39;).show(); //hide submit button  
        $("#output").html("");    
    }  
    else  
    {  
        //Output error to older unsupported browsers that doesn&#39;t support HTML5 File API  
        $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");  
        return false;  
    }  
}  
  
//function to format bites bit.ly/19yoIPO  
function bytesToSize(bytes) {  
   var sizes = [&#39;Bytes&#39;, &#39;KB&#39;, &#39;MB&#39;, &#39;GB&#39;, &#39;TB&#39;]; 
   if (bytes == 0) return &#39;0 Bytes&#39;; 
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); 
   return Math.round(bytes / Math.pow(1024, i), 2) + &#39; &#39; + sizes[i];  
}  
  
</script>
Copier après la connexion




processupload.php

PHP Code

<?php  
if(isset($_POST))  
{  
    ############ Edit settings ##############  
    $ThumbSquareSize        = 200; //Thumbnail will be 200x200  
    $BigImageMaxSize        = 500; //Image Maximum height or width  
    $ThumbPrefix            = "thumb_"; //Normal thumb Prefix  
    $DestinationDirectory   = &#39;../upload/&#39;; //specify upload directory ends with / (slash)  
    $Quality                = 90; //jpeg quality  
    ##########################################  
      
    //check if this is an ajax request  
    if (!isset($_SERVER[&#39;HTTP_X_REQUESTED_WITH&#39;])){  
        die();  
    }  
      
    // check $_FILES[&#39;ImageFile&#39;] not empty  
    if(!isset($_FILES[&#39;ImageFile&#39;]) || !is_uploaded_file($_FILES[&#39;ImageFile&#39;][&#39;tmp_name&#39;]))  
    {  
            die(&#39;Something wrong with uploaded file, something missing!&#39;); // output error when above checks fail.  
    }  
      
    // Random number will be added after image name  
    $RandomNumber   = rand(0, 9999999999);   
  
    $ImageName      = str_replace(&#39; &#39;,&#39;-&#39;,strtolower($_FILES[&#39;ImageFile&#39;][&#39;name&#39;])); //get image name  
    $ImageSize      = $_FILES[&#39;ImageFile&#39;][&#39;size&#39;]; // get original image size  
    $TempSrc        = $_FILES[&#39;ImageFile&#39;][&#39;tmp_name&#39;]; // Temp name of image file stored in PHP tmp folder  
    $ImageType      = $_FILES[&#39;ImageFile&#39;][&#39;type&#39;]; //get file type, returns "image/png", image/jpeg, text/plain etc.  
  
    //Let&#39;s check allowed $ImageType, we use PHP SWITCH statement here  
    switch(strtolower($ImageType))  
    {  
        case &#39;image/png&#39;: 
            //Create a new image from file  
            $CreatedImage =  imagecreatefrompng($_FILES[&#39;ImageFile&#39;][&#39;tmp_name&#39;]); 
            break; 
        case &#39;image/gif&#39;: 
            $CreatedImage =  imagecreatefromgif($_FILES[&#39;ImageFile&#39;][&#39;tmp_name&#39;]); 
            break;           
        case &#39;image/jpeg&#39;: 
        case &#39;image/pjpeg&#39;: 
            $CreatedImage = imagecreatefromjpeg($_FILES[&#39;ImageFile&#39;][&#39;tmp_name&#39;]); 
            break; 
        default: 
            die(&#39;Unsupported File!&#39;); //output error and exit 
    } 
     
    //PHP getimagesize() function returns height/width from image file stored in PHP tmp folder. 
    //Get first two values from image, width and height.  
    //list assign svalues to $CurWidth,$CurHeight 
    list($CurWidth,$CurHeight)=getimagesize($TempSrc); 
     
    //Get file extension from Image name, this will be added after random name 
    $ImageExt = substr($ImageName, strrpos($ImageName, &#39;.&#39;)); 
    $ImageExt = str_replace(&#39;.&#39;,&#39;&#39;,$ImageExt); 
     
    //remove extension from filename 
    $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);  
     
    //Construct a new name with random number and extension. 
    $NewImageName = $ImageName.&#39;-&#39;.$RandomNumber.&#39;.&#39;.$ImageExt; 
     
    //set the Destination Image 
    $thumb_DestRandImageName    = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumbnail name with destination directory 
    $DestRandImageName          = $DestinationDirectory.$NewImageName; // Image with destination directory 
     
    //Resize image to Specified Size by calling resizeImage function. 
    if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType)) 
    { 
        //Create a square Thumbnail right after, this time we are using cropImage() function 
        if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType)) 
            { 
                echo &#39;Error Creating thumbnail&#39;; 
            } 
        /* 
        We have succesfully resized and created thumbnail image 
        We can now output image to user&#39;s browser or store information in the database  
        */  
        echo &#39;<table width="100%" border="0" cellpadding="4" cellspacing="0">&#39;;  
        echo &#39;<tr>&#39;;  
        echo &#39;<td align="center"><img src="../upload/&#39;.$ThumbPrefix.$NewImageName.&#39;" alt="Thumbnail"></td>&#39;;  
        echo &#39;</tr><tr>&#39;;  
        echo &#39;<td align="center"><img src="../upload/&#39;.$NewImageName.&#39;" alt="Resized Image"></td>&#39;;  
        echo &#39;</tr>&#39;;  
        echo &#39;</table>&#39;;  
  
        /* 
        // Insert info into database table! 
        mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath) 
        VALUES ($DestRandImageName, $thumb_DestRandImageName, &#39;uploads/&#39;)"); 
        */  
  
    }else{  
        die(&#39;Resize Error&#39;); //output error  
    }  
}  
  
  
// This function will proportionally resize image   
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)  
{  
    //Check Image size is not 0  
    if($CurWidth <= 0 || $CurHeight <= 0)   
    {  
        return false;  
    }  
      
    //Construct a proportional size of new image  
    $ImageScale         = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);   
    $NewWidth           = ceil($ImageScale*$CurWidth);  
    $NewHeight          = ceil($ImageScale*$CurHeight);  
    $NewCanves          = imagecreatetruecolor($NewWidth, $NewHeight);  
      
    // Resize Image  
    if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))  
    {  
        switch(strtolower($ImageType))  
        {  
            case &#39;image/png&#39;:  
                imagepng($NewCanves,$DestFolder);  
                break;  
            case &#39;image/gif&#39;:  
                imagegif($NewCanves,$DestFolder);  
                break;            
            case &#39;image/jpeg&#39;:  
            case &#39;image/pjpeg&#39;:  
                imagejpeg($NewCanves,$DestFolder,$Quality);  
                break;  
            default:  
                return false;  
        }  
    //Destroy image, frees memory     
    if(is_resource($NewCanves)) {imagedestroy($NewCanves);}   
    return true;  
    }  
  
}  
  
//This function corps image to create exact square images, no matter what its original size!  
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)  
{      
    //Check Image size is not 0  
    if($CurWidth <= 0 || $CurHeight <= 0)   
    {  
        return false;  
    }  
      
    //abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9  
    if($CurWidth>$CurHeight)  
    {  
        $y_offset = 0;  
        $x_offset = ($CurWidth - $CurHeight) / 2;  
        $square_size    = $CurWidth - ($x_offset * 2);  
    }else{  
        $x_offset = 0;  
        $y_offset = ($CurHeight - $CurWidth) / 2;  
        $square_size = $CurHeight - ($y_offset * 2);  
    }  
      
    $NewCanves  = imagecreatetruecolor($iSize, $iSize);   
    if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))  
    {  
        switch(strtolower($ImageType))  
        {  
            case &#39;image/png&#39;:  
                imagepng($NewCanves,$DestFolder);  
                break;  
            case &#39;image/gif&#39;:  
                imagegif($NewCanves,$DestFolder);  
                break;            
            case &#39;image/jpeg&#39;:  
            case &#39;image/pjpeg&#39;:  
                imagejpeg($NewCanves,$DestFolder,$Quality);  
                break;  
            default:  
                return false;  
        }  
    //Destroy image, frees memory     
    if(is_resource($NewCanves)) {imagedestroy($NewCanves);}   
    return true;  
  
    }  
        
}
Copier après la connexion



以上就是我们要介绍的ajax无刷新图片上传功能了,其实就是通过异步模式提交给php然后由php上传图片并且生成小图返回给指定的id的htm元素模块即可。

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Recommandations populaires
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal