设为首页 收藏本站
查看: 408|回复: 0

[经验分享] jquery php多文件上传

[复制链接]

尚未签到

发表于 2017-3-26 11:41:14 | 显示全部楼层 |阅读模式
多文件上传

DSC0000.jpg
演示
index.php
PHP Code

  • <div id="uploaderform">  
  • <form action="upload.php" method="post" enctype="multipart/form-data" name="UploadForm" id="UploadForm">  
  •     <h1>jquery php多文件上传(本例限制为3个文件)</h1>   
  •     <label>文件  
  •     <span class="small"><a href="#" id="AddMoreFileBox">添加上传框</a></span>  
  •     </label>  
  •     <div id="AddFileInputBox"><input id="fileInputBox" style="margin-bottom: 5px;" type="file"  name="file[]"/></div>  
  •     <div class="sep_s"></div>  
  •       
  •     <label>介绍  
  •      
  •     </label>  
  •     <div><input name="username" type="text" id="username" value="freejs.net" /></div>  
  •       
  •      
  •     <button type="submit" class="button" id="SubmitButton">Upload</button>  
  •       
  •     <div id="progressbox"><div id="progressbar"></div ><div id="statustxt">0%</div ></div>  
  • </form>  
  • </div>  
  • <div id="uploadResults">  
  •     <div align="center" style="margin:20px;"><a href="#" id="ShowForm">打开/隐藏 表单</a></div>  
  •     <div id="output"></div>  
  • </div>  


js文件
JavaScript Code

  • <script type="text/javascript">   
  • $(document).ready(function() {   
  • //elements  
  • var progressbox         = $('#progressbox'); //progress bar wrapper  
  • var progressbar         = $('#progressbar'); //progress bar element  
  • var statustxt           = $('#statustxt'); //status text element  
  • var submitbutton        = $("#SubmitButton"); //submit button  
  • var myform              = $("#UploadForm"); //upload form  
  • var output              = $("#output"); //ajax result output element  
  • var completed           = '0%'//initial progressbar value  
  • var FileInputsHolder    = $('#AddFileInputBox'); //Element where additional file inputs are appended  
  • var MaxFileInputs       = 3; //Maximum number of file input boxs  
  •   
  • // adding and removing file input box  
  • var i = $("#AddFileInputBox div").size() + 1;  
  • $("#AddMoreFileBox").click(function () {  
  •         event.returnValue = false;  
  •         if(i < MaxFileInputs)  
  •         {  
  •             $('<span><input type="file" id="fileInputBox" size="20" name="file[]" class="addedInput" value=""/><a href="#" class="removeclass small2"><img src="images/close_icon.gif" border="0" /></a></span>').appendTo(FileInputsHolder);  
  •             i++;  
  •         }  
  •         return false;  
  • });  
  •   
  • $("body").on("click",".removeclass"function(e){  
  •         event.returnValue = false;  
  •         if( i > 1 ) {  
  •                 $(this).parents('span').remove();i--;  
  •         }  
  •           
  • });   
  •   
  • $("#ShowForm").click(function () {  
  •   $("#uploaderform").slideToggle(); //Slide Toggle upload form on click  
  • });  
  •       
  • $(myform).ajaxForm({  
  •     beforeSend: function() { //brfore sending form  
  •         submitbutton.attr('disabled'''); // disable upload button  
  •         statustxt.empty();  
  •         progressbox.show(); //show progressbar  
  •         progressbar.width(completed); //initial value 0% of progressbar  
  •         statustxt.html(completed); //set status text  
  •         statustxt.css('color','#000'); //initial color of status text  
  •           
  •     },  
  •     uploadProgress: function(event, position, total, percentComplete) { //on progress  
  •         progressbar.width(percentComplete + '%'//update progressbar percent complete  
  •         statustxt.html(percentComplete + '%'); //update status text  
  •         if(percentComplete>50)  
  •             {  
  •                 statustxt.css('color','#fff'); //change status text to white after 50%  
  •             }else{  
  •                 statustxt.css('color','#000');  
  •             }  
  •               
  •         },  
  •     complete: function(response) { // on complete  
  •         output.html(response.responseText); //update element with received data  
  •         myform.resetForm();  // reset form  
  •         submitbutton.removeAttr('disabled'); //enable submit button  
  •         progressbox.hide(); // hide progressbar  
  •         $("#uploaderform").slideUp(); // hide form after upload  
  •     }  
  • });  
  •   
  • });   
  • </script>   


 uoload.php
 
PHP Code

  • <noscript>  
  • <div align="center"><a href="index.php">Go Back To Upload Form</a></div><!-- If javascript is disabled -->  
  • </noscript>  
  • <?php  
  • //If you face any errors, increase values of "post_max_size", "upload_max_filesize" and "memory_limit" as required in php.ini  
  •   
  •  //Some Settings  
  • $ThumbSquareSize        = 200; //Thumbnail will be 200x200  
  • $BigImageMaxSize        = 500; //Image Maximum height or width  
  • $ThumbPrefix            = "thumb_"//Normal thumb Prefix  
  • $DestinationDirectory   = '../upload/'//Upload Directory ends with / (slash)  
  • $Quality                = 90;  
  •   
  • //ini_set('memory_limit', '-1'); // maximum memory!  
  •   
  • foreach($_FILES as $file)  
  • {  
  • // some information about image we need later.  
  • $ImageName      = $file['name'];  
  • $ImageSize      = $file['size'];  
  • $TempSrc        = $file['tmp_name'];  
  • $ImageType      = $file['type'];  
  •   
  •   
  • if (is_array($ImageName))   
  • {  
  •     $c = count($ImageName);  
  •       
  •     echo  '<ul>';  
  •       
  •     for ($i=0; $i < $c$i++)  
  •     {  
  •         $processImage           = true;   
  •         $RandomNumber           = rand(0, 9999999999);  // We need same random name for both files.  
  •           
  •         if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))  
  •         {  
  •             echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>'//output error  
  •         }  
  •         else  
  •         {  
  •             //Validate file + create image from uploaded file.  
  •             switch(strtolower($ImageType[$i]))  
  •             {  
  •                 case 'image/png':  
  •                     $CreatedImage = imagecreatefrompng($TempSrc[$i]);  
  •                     break;  
  •                 case 'image/gif':  
  •                     $CreatedImage = imagecreatefromgif($TempSrc[$i]);  
  •                     break;  
  •                 case 'image/jpeg':  
  •                 case 'image/pjpeg':  
  •                     $CreatedImage = imagecreatefromjpeg($TempSrc[$i]);  
  •                     break;  
  •                 default:  
  •                     $processImage = false; //image format is not supported!  
  •             }  
  •             //get Image Size  
  •             list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);  
  •   
  •             //Get file extension from Image name, this will be re-added after random name  
  •             $ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));  
  •             $ImageExt = str_replace('.','',$ImageExt);  
  •       
  •             //Construct a new image name (with random number added) for our new image.  
  •             $NewImageName = $RandomNumber.'.'.$ImageExt;  
  •   
  •             //Set the Destination Image path with Random Name  
  •             $thumb_DestRandImageName    = $DestinationDirectory.$ThumbPrefix.$NewImageName//Thumb name  
  •             $DestRandImageName          = $DestinationDirectory.$NewImageName//Name for Big Image  
  •   
  •             //Resize image to our Specified Size by calling resizeImage function.  
  •             if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))  
  •             {  
  •                 //Create a square Thumbnail right after, this time we are using cropImage() function  
  •                 if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))  
  •                     {  
  •                         echo 'Error Creating thumbnail';  
  •                     }  
  •                     /* 
  •                     At this point we have succesfully resized and created thumbnail image 
  •                     We can render image to user's browser or store information in the database 
  •                     For demo, we are going to output results on browser. 
  •                     */  
  •                       
  •                     //Get New Image Size  
  •                     list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);  
  •                       
  •                     echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">'; 
  •                     echo '<tr>'; 
  •                     echo '<td align="center"><img src="../upload/'.$ThumbPrefix.$NewImageName.'" alt="Thumbnail" height="'.$ThumbSquareSize.'" width="'.$ThumbSquareSize.'"></td>'; 
  •                     echo '</tr><tr>'; 
  •                     echo '<td align="center"><img src="../upload/'.$NewImageName.'" alt="Resized Image" height="'.$ResizedHeight.'" width="'.$ResizedWidth.'"></td>'; 
  •                     echo '</tr>'; 
  •                     echo '</table>'; 
  •                     /* 
  •                     // Insert info into database table! 
  •                     mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath) 
  •                     VALUES ($DestRandImageName, $thumb_DestRandImageName, '../upload/')"); 
  •                     */ 
  •  
  •             }else{ 
  •                 echo '<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>! Please check if file is supported</div>'; //output error 
  •             } 
  •              
  •         } 
  •          
  •     } 
  •     echo '</ul>'; 
  •     } 
  • } 
  •      
  • // 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); 
  •      
  •     if($CurWidth < $NewWidth || $CurHeight < $NewHeight) 
  •     { 
  •         $NewWidth = $CurWidth; 
  •         $NewHeight = $CurHeight; 
  •     } 
  •     $NewCanves  = imagecreatetruecolor($NewWidth, $NewHeight); 
  •     // Resize Image 
  •     if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight)) 
  •     { 
  •         switch(strtolower($ImageType)) 
  •         { 
  •             case 'image/png': 
  •                 imagepng($NewCanves,$DestFolder); 
  •                 break; 
  •             case 'image/gif': 
  •                 imagegif($NewCanves,$DestFolder); 
  •                 break;           
  •             case 'image/jpeg': 
  •             case 'image/pjpeg': 
  •                 imagejpeg($NewCanves,$DestFolder,$Quality); 
  •                 break; 
  •             default: 
  •                 return false; 
  •         } 
  •     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" 
  •     //http://www.abeautifulsite.net/blog/2009/08/cropping-an-image-to-make-square-thumbnails-in-php/ 
  •     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 'image/png': 
  •                 imagepng($NewCanves,$DestFolder); 
  •                 break; 
  •             case 'image/gif': 
  •                 imagegif($NewCanves,$DestFolder); 
  •                 break;           
  •             case 'image/jpeg': 
  •             case 'image/pjpeg':  
  •                 imagejpeg($NewCanves,$DestFolder,$Quality);  
  •                 break;  
  •             default:  
  •                 return false;  
  •         }  
  •     if(is_resource($NewCanves)) {   
  •       imagedestroy($NewCanves);   
  •     }   
  •     return true;  
  •   
  •     }  
  •         
  • }  


 
  
原文地址:http://www.freejs.net/article_biaodan_45.html

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-355584-1-1.html 上篇帖子: [php]前端控制器 下篇帖子: (转)php 5.3编译PDO问题
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表