PHP implements Multi-graph upload (combined with the uploadify plug-in) Ideas analysis, multi-graph uploadify

Source: Internet
Author: User
Tags php file upload php foreach

PHP implements Multi-graph upload (combined with the uploadify plug-in) Ideas analysis, multi-graph uploadify

The example in this article describes how to implement multigraph upload in PHP. We will share this with you for your reference. The details are as follows:

1. You can delete an existing image.
2. There is a new button
3. Click the Add button to jump out of the frame Box.
4. Implement Asynchronous Image Upload and timely effect in the frame Box
5. Call the callback function after the upload is successful.
6. You can delete images in the pop-up box.
7. Click Save in the frame pop-up box to display the image to the page through js.
8. Click Save on the page to save the image data to the database.

<? Php foreach ($ info ['product _ img '] as $ product_img) {?> <Div style = "width: 100px; text-align: center; margin: 5px; display: inline-block; "class =" goods_xc "> <input type =" hidden "value =" <? Php echo $ product_img ['img '];?> "Name =" product_img [] "> <a onclick =" "href =" <? Php echo $ product_img ['img '];?> "Target =" _ blank ">  "> </A> <br> <a href =" javascript: void (0) "onclick =" ClearPicArr2 (this, '<? Php echo $ product_img ['img '];?> ') "> Delete </a> </div> <? Php }?> <Div class = "goods_xc" style = "width: 100px; text-align: center; margin: 5px; display: inline-block; "> <input type =" hidden "name =" product_img [] "/> <a href =" javascript: void (0); "onclick =" GetUploadify (10, '', 'product', 'Call _ back2');">  Add-button.jpg "width =" 100 "height =" 100 "/> </a> <br/> <a href =" javascript: void (0) "> </a> </div>

Comment: Call the GetUploadify method when you click it.

/** Upload image back-end dedicated * @ access public * @ null int one-time upload image graph * @ elementid string after successful upload, return to the path to insert the specified ID element * @ path string specified upload save the folder, by default, the Public/upload/temp/directory * @ callback string callback function exists. (The save path string is returned for a single image, and the path array is returned for multiple images.) */function GetUploadify (num, elementid, path, callback) {var pc_hash = $ ('# pc_hash '). val (); var upurl = '? M = admin & c = upload & a = upload & num = '+ num +' & input = '+ elementid +' & path = '+ path +' & func = '+ callback + '& pc_hash =' + pc_hash; var iframe_str = '<iframe frameborder = "0"'; iframe_str = iframe_str + 'id = uploadify '; iframe_str = iframe_str + 'src =' + upurl; iframe_str = iframe_str + 'allowtransparency = "true" class = "uploadframe" scrolling = "no"> '; iframe_str = iframe_str +' </iframe> '; $ ("body "). append (iframe_str); $ ("iframe. uploadframe ").css (" height ", (document).height()).css (" width "," 100% ").css (" position "," absolute ").css (" left "," 0px ").css (" top ", "0px" ).css ("z-index", "999999 "). show (); $ (window ). resize (function () {$ ("iframe. uploadframe "mirror.css (" height ", $ (document ). height ()). show ();});}

Comment: generate an iframe box.

public function upload(){    $func = $_REQUEST['func'];    $path = $_REQUEST['path'] ? $_REQUEST['path'] :'temp';    $info = array(      'num'=> $_REQUEST['num'],      'title' => '',           'upload' =>'?m=admin&c=upload&a=imageUp&savepath='.$path.'&pictitle=banner&dir=images&pc_hash='.$_SESSION['pc_hash'],      'size' => '4M',      'type' =>'jpg,png,gif,jpeg',      'input' => $_REQUEST['input'],      'func' => empty($func) ? 'undefined' : $func,    );    include $this->admin_tpl('upload_upload');}
<! DOCTYPE html> 

Comment: Call the uploadify plug-in

$(function() {  $('#uploadify').uploadify({      'auto'      : true,      'method'     : 'post',      'multi'      : true,      'swf'       : '<?php echo PLUGIN_STATICS_PATH?>uploadify/uploadify.swf',      'uploader'    : '<?php echo $info["upload"];?>',      'progressData'  : 'all',      'queueSizeLimit' : '<?php echo $info["num"];?>',      'uploadLimit'   : 5,      'fileSizeLimit'  : '20000KB',      'fileTypeDesc'  : 'Image Files',      'fileTypeExts'  : '*.jpeg; *.jpg; *.png; *.gif',      'buttonImage'   : '<?php echo PLUGIN_STATICS_PATH?>uploadify/select.png',      'queueID'     : 'fileQueue',      'onUploadStart'  : function(file){        $('#uploadify').uploadify('settings', 'formData', {'iswatermark':$("#iswatermark").is(':checked')});              },      'onUploadSuccess' : function(file, data, response){        $(".fileWarp ul").append(SetImgContent(data));        SetUploadFile();      }    });});

Comments: The form submits the image file to the server and calls the callback function after the file is successfully submitted.

/*** @ Function imageUp */public function imageUp () {// file input, now you need to save it // process the uploaded data and return the data // The Name Of The description form in the upload image box, $ title = htmlspecialchars ($ _ REQUEST ['pictitle'], ENT_QUOTES); // $ path = htmlspecialchars ($ _ REQUEST ['dir'], ENT_QUOTES); $ savepath = htmlspecialchars ($ _ REQUEST ['savepath'], ENT_QUOTES ); $ up = new think_upload (); $ path = '. /uploadfile /'. $ savepath; // set attributes (the uploaded location, size, type, and name must be randomly generated) $ up-> set ("path", $ path ); $ up-> set ("maxsize", 2000000); $ up-> set ("allowtype", array ("gif", "png", "jpg ", "jpeg"); $ up-> set ("israndname", true); // you can upload files by using the upload method in the object, the upload form name must be passed. if the success returns true, the failure returns false if ($ up-> upload ("Filedata ")) {$ name = $ up-> getFileName (); $ return_data ['url'] = $ path. '/'. $ name; $ return_data ['title'] = $ title; $ return_data ['state'] = 'success'; exit (json_encode ($ return_data ));} else {$ return_data ['state'] = 'failed'; $ return_data ['msg '] = $ up-> getErrorMsg (); exit (json_encode ($ return_data ));}}

Comment: The background processes the Image Upload form request and returns the image path.

<? Php/*** file: fileupload. class. php File Upload class FileUpload * this class of instance objects are used to process uploaded files. You can upload a file or upload multiple files simultaneously */class think_upload {private $ path = ". /uploadfile "; // the path for saving the uploaded file: private $ allowtype = array ('jpg ', 'gif', 'png '); // sets the type of the file to be uploaded to private $ maxsize = 1000000; // sets the size (in bytes) of the file to private $ israndname = true; // sets whether to rename the file at random, false not random private $ originName; // source file name private $ tmpFileName; // temporary file name private $ fileType; // file type (File suffix) private $ fileSize; // file size private $ newFileName; // new file name private $ errorNum = 0; // error code private $ errorMess = ""; // Error Report Message/*** used to set Member attributes ($ path, $ allowtype, $ maxsize, $ israndname) * multiple attribute values can be set at a time through a consistent operation * @ param string $ key member attribute name (Case Insensitive) * @ param mixed $ val refers to the value set for the member attribute * @ return object returns its own object $ this, which can be used for consistent operations */function set ($ key, $ val) {$ key = strtolower ($ key); if (array_key_exists ($ key, get_class_vars (get_c Lass ($ this) {$ this-> setOption ($ key, $ val);} return $ this ;} /*** call this method to upload a file * @ param string $ fileFile form name * @ return bool true if the file is uploaded successfully */function upload ($ fileField) {$ return = true;/* check whether the file path is legal */if (! $ This-> checkFilePath () {$ this-> errorMess = $ this-> getError (); return false ;} /* extract the file upload information and assign it to the variable */$ name = $ _ FILES [$ fileField] ['name']; $ tmp_name = $ _ FILES [$ fileField] ['tmp _ name']; $ size = $ _ FILES [$ fileField] ['SIZE']; $ error = $ _ FILES [$ fileField] ['error']; /* if multiple files are uploaded, $ file ["name"] will be an array */if (is_Array ($ name) {$ errors = array (); /* multiple files are uploaded cyclically. This loop only checks the function of uploading files and does not actually upload files */for ($ I = 0; $ I <count ($ Name); $ I ++) {/* set file information */if ($ this-> setFiles ($ name [$ I], $ tmp_name [$ I], $ size [$ I], $ error [$ I]) {if (! $ This-> checkFileSize () |! $ This-> checkFileType () {$ errors [] = $ this-> getError (); $ return = false ;}} else {$ errors [] = $ this-> getError (); $ return = false;}/* if there is a problem, re-initialize the attribute */if (! $ Return) $ this-> setFiles ();} if ($ return) {/* variable array for storing all uploaded file names */$ fileNames = array (); /* if multiple uploaded files are valid, the file will be uploaded to the server through a soul loop */for ($ I = 0; $ I <count ($ name ); $ I ++) {if ($ this-> setFiles ($ name [$ I], $ tmp_name [$ I], $ size [$ I], $ error [$ I]) {$ this-> setNewFileName (); if (! $ This-> copyFile () {$ errors [] = $ this-> getError (); $ return = false ;} $ fileNames [] = $ this-> newFileName; }}$ this-> newFileName = $ fileNames;} $ this-> errorMess = $ errors; return $ return; /* Processing Method for uploading a single file */} else {/* setting file information */if ($ this-> setFiles ($ name, $ tmp_name, $ size, $ error )) {/* check the size and type before uploading */if ($ this-> checkFileSize () & $ this-> checkFileType ()) {/* set a new file name */$ this-> setNewFileName ();/* upload a file If the return value is 0, the return value is successful. if ($ this-> copyFile () {return true;} else {$ return = false ;}} else {$ return = false;} // if $ return is false, an error occurs. Save the error information in the errorMess attribute if (! $ Return) $ this-> errorMess = $ this-> getError (); return $ return ;}} /*** get the name of the uploaded file * @ param void No parameter * @ return string the name of the new file after the upload, if an array */public function getFileName () {return $ this-> newFileName;}/*** is returned after the upload fails, upload error message * @ param void No parameter * @ return string returns the Upload File error message report. If Multifile upload returns an array */public function getErrorMsg () {return $ this-> errorMess;}/* Set upload error information */private function getError () {$ Str = "An error occurred while uploading the file <font color = 'red' >{$ this-> originName} </font>:"; switch ($ this-> errorNum) {case 4: $ str. = "no file is uploaded"; break; case 3: $ str. = "only part of the file is uploaded"; break; case 2: $ str. = "the size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form"; break; case 1: $ str. = "the uploaded file exceeds php. value restricted by the upload_max_filesize option in ini "; break; case-1: $ str. = "unsupported type"; break; case-2: $ str. = "the file is too large, and the uploaded file cannot exceed {$ this-> maxsize} bytes"; break; case-3: $ s Tr. = "Upload Failed"; break; case-4: $ str. = "An error occurred while creating the Upload File directory. Please specify the upload directory again"; break; case-5: $ str. = "The path of the file to be uploaded must be specified"; break; default: $ str. = "Unknown error";} return $ str. '<br>';}/* set content related to $ _ FILES */private function setFiles ($ name = "", $ tmp_name = "", $ size = 0, $ error = 0) {$ this-> setOption ('errornum', $ error); if ($ error) return false; $ this-> setOption ('originname ', $ name); $ this-> setOption ('tmpfilename', $ tmp_name); $ ar YStr = explode (". ", $ name); $ this-> setOption ('filetype', strtolower ($ aryStr [count ($ aryStr)-1]); $ this-> setOption ('filesize', $ size); return true;}/* set the value for a single member attribute */private function setOption ($ key, $ val) {$ this-> $ key = $ val;}/* set the name of the uploaded file */private function setNewFileName () {if ($ this-> israndname) {$ this-> setOption ('newfilename', $ this-> proRandName ();} else {$ this-> setOption ('newfilename', $ This-> originName) ;}/ * check whether the uploaded file is of a valid type */private function checkFileType () {if (in_array (strtolower ($ this-> fileType), $ this-> allowtype) {return true;} else {$ this-> setOption ('errornum ', -1); return false;}/* check whether the uploaded file is the allowed size */private function checkFileSize () {if ($ this-> fileSize> $ this-> maxsize) {$ this-> setOption ('errornum',-2); return false ;} else {return true;}/* check whether there are stored uploads File directory */private function checkFilePath () {if (empty ($ this-> path) {$ this-> setOption ('errornum',-5 ); return false;} if (! File_exists ($ this-> path) |! Is_writable ($ this-> path) {if (! @ Mkdir ($ this-> path, 0755) {$ this-> setOption ('errornum',-4); return false ;}} return true ;} /* set the random file name */private function proRandName () {$ fileName = date ('ymdhis '). "_". rand (100,999); return $ fileName. '. '. $ this-> fileType;}/* copy the uploaded file to the specified location */private function copyFile () {if (! $ This-> errorNum) {$ path = rtrim ($ this-> path ,'/'). '/'; $ path. = $ this-> newFileName; if (@ move_uploaded_file ($ this-> tmpFileName, $ path) {return true;} else {$ this-> setOption ('errornum ', -3); return false ;}} else {return false ;}}}

Comment: PHP File Upload class.

After processing, the image data is deleted and the corresponding file is uploaded, reducing the server space pressure.

Public function delete () {$ id = intval ($ _ GET ['id']); $ this-> db-> delete (array ('id' => $ id )); // traverse and delete the original image $ product_img = $ this-> product_img_db-> select (array ('product _ id' => $ id )); foreach ($ product_img as $ k => $ v) {unlink ($ v ['img ']);} // delete table data $ this-> product_img_db-> delete (array ('product _ id' => $ id); exit ("1 ");}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.