Implement Magento Multi-File upload code function development

Source: Internet
Author: User

Uploading a single file in Magento is simple, you can directly add the following component directly in the Inherited Mage_adminhtml_block_widget_form class field: For Picture: $fieldset->addfield (' Test_ Pic ', ' image ', Array (' label ' = ' + ' label ', ' name ' = ' test_pic ',)); For files: $fieldset->addfield (' test_file ', ' file ', Array (' label ' = ' + ' tag ', ' name ' = ' test_file ',)); Only use the Varien_file_uploader tool class in the controller action corresponding to the background to get it. But this component can only handle single file upload, so what do you do for multi-file uploads? Through the observation of the original Magento function, only in the product editing or creation, there is a upload multi-image function (see), the function is to achieve a multi-file upload!
Magento Product picture multiple file upload   So I try to read and understand its original code, I know that the original in the Magento processing multi-file upload using a Flash plug-in called Flex Uploader implementation, and the corresponding Magento system to a packaged Block class for processing: Mage_adminhtml_block_media_uploader, the following on a personal implementation of a multi-file upload plugin to talk about the implementation of the steps.  1. First, the implementation of block class   in the implementation of multi-file upload, you need to implement the foreground HTML page, here by customizing a block class to include the Flex uploader component to implement, this class can inherit the normal background block class: Mage_ Adminhtml_block_widget, add the Mage_adminhtml_block_media_uploader sub-block as follows in its reset _preparelayout method block: protected function _preparelayout () {   //Add Mage_adminhtml_block_media_uploader sub-block block    $this SetChild (' uploader ', $this->getlayout ()->createblock (' Adminhtml/media_uploader '));     $ This->getchild (' uploader ')->getconfig ()            //File Upload processing action    & nbsp      ->seturl (Mage::getmodel (' Adminhtml/url ')->addsessionparam ()->geturl (' */material/ Upload ')            ->setfilefield (' material_files ')            ->setfilteRS (                ' all ' = = Array (          &NBS P         ' label ' = Mage::helper (' adminhtml ')->__ (' All Files '),        &NBSP ;           ' files ' = Array (' *. * ')  //description of files receiving any suffix           &NBSP ;    )    );     return parent::_preparelayout ();}   Accordingly, the sub-block named uploader is output in the Phtml view template corresponding to the Block class:  <?php echo $this->getchildhtml (' uploader ');?>   If all goes well, it will be output in the custom background page see these two buttons: 
Uploader components   As above Block code reference: Mage_adminhtml_block_catalog_product_helper_form_gallery_content as above phtml template reference: App\ DESIGN\ADMINHTML\DEFAULT\DEFAULT\TEMPLATE\CATALOG\PRODUCT\HELPER\GALLERY.PHTML2. Implementing upload processing action  When you see the two buttons on the page, stating that your page has successfully added the Flex uploader plugin, then we need to implement the corresponding background upload processing action, remember the above SetUrl (URL) method? This method specifies that when the user selects the file, click the "Upload File" button to receive the action Url of the file, here we set a name for this upload action, the following can give its processing code:  public function Uploadaction () {    try {       //Note the material_files here is the same name as the Setfilefield () method in block above         $uploader = new Mage_core_model_file_uploader (' Material_files ');       / /allow the upload file suffix name, comment out here to allow all suffix files, of course, the suffix named PHP is forbidden//      $uploader->setallowedextensions (' txt ', ' PDF ', ' Doc ', ' docx ');        $uploader->setallowrenamefiles (true);        $ Uploader->setfilesdispersion (True);        $result = $uploader->save ($this Getbasetmpmediapath ());//     mage::log ($result, NULL, ' Commodity___test.log ');        /**          * workaround for prototype 1.7 methods "Isjson", "Evaljson" on Windows os    & nbsp    */        $result [' tmp_name '] = Str_replace (DS, "/", $result [' Tmp_name ']);        $result [' path '] = Str_replace (DS, "/", $result [' path ']);         $result [' url '] = $ This->gettmpmediaurl ($result [' file ']);        $result [' file '] = $result [' file '];    & nbsp   $result [' cookie '] = Array (            ' name ' = Session_name (),    &NBSP ;       ' value ' = $this->_getsession ()->getsessionid (),            ' Lifetime ' = $this->_getsession ()->getcookielifetime (),            ' path ' = $ This->_getsession ()-&GT;getcookiepath (),            ' domain ' = $this->_getsession ()->getcookiedomain ()        );   } catch (Exception $e) {        $result = array (' ERROR ' = = $e->getmessage (), ' errorcode ' = $e->getcode ());   }// mage::log ($result, NULL, ' Commodity___test.log ');    $this->getresponse ()->setbody (Mage::helper (' core ')->jsonencode ($ result));}  private function Getbasetmpmediapath () {    return Mage::getbasedir (' media '). Ds. ' Commodity '. Ds. ' Material ';}  private function Gettmpmediaurl ($file) {    $file = Str_replace (DS, '/', $file);     if (su BSTR ($file, 0, 1) = = '/') {        $file = substr ($file, 1);   }     return Mage::getbaseurl (' media '). '/commodity/material/'. $file;}   can see that processing the upload file, using a tool class named Mage_core_model_file_uploader, and the JSON message passed to the foreground encoded, that is, Flex upThe loader plugin uploads every file through Ajax.   by releasing the Mage::log () method, we can further understand that after the Mage_core_model_file_uploader tool class calls the Save method, the data format returned is as follows:  array (    [Name] = file name. suffix     [type] = = application/octet-stream    [Tmp_name] + <apache Set Pro Catalog >\tmp\phpBA95.tmp    [ERROR] = 0    [size] = 4907    [path] + <magento root Catalog >\media\commodity\material    [file] +/v/i/rename filename. suffix)   above is the value of the original $result variable, Of course I did some custom processing to make the $result variable more consistent with the format data of my plugin, and you can customize the processing according to your own situation.   Above code reference: mage_adminhtml_catalog_product_gallerycontroller 3. Reception AJAX reception JSON processing   as above, with the front page, The background upload handles the action, and the next thing we do is to be able to receive the JSON information returned in the upload action on the foreground page, how should we receive JSON for this Flex uploader plugin?   By viewing the <magento root directory >\js\mage\adminhtml\flexuploader.jsjs file we know, Flex. The uploader plugin's upload success callback function is onfilescomplete; To receive JSON information above the background, we only need to set the Onfilescomplete method of the Flex.uploader instance object under the current page.   That's the question again, how do we get the Flex.uploader instance object for the current page?   Actually Magento is ready for us, do you still remember the block uploader object in the blocks class above? WildcardAfter it we can get the Flex.uploader instance object, the specific code is as follows (in the phtml template <script> tag):  <script type= "Text/javascript" >var uploader = <?php echo $this->getchild (' uploader ')->getjsobjectname ();? >;uploader.onfilescomplete = function (files) {   //Receive processing JSON data uploaded into function}</script>  The above code reference: <magento root directory >\js\mage\ The Handleuploadcomplete method in Adminhtml\product.js.  4. Finally   According to the above rough introduction I think we should be able to use the Flex uploader plugin to upload multiple files have a certain revelation, the final step is to get the upload back to the JSON information in the foreground using hidden saved up, Then through the corresponding form to the background operation to write to the database, to achieve the final finishing work; Here you can refer to the <magento root directory >\js\mage\adminhtml\ Product.js method, the JSON information into a string to save, corresponding to the background in the use of JOSN decoding to get the object array manipulation processing.   at the very end of the question is how to keep multiple Flex uploader plug-ins in a single page, which may be encountered in the Magento background using the tab component. When using multiple Flex uploader plugins in a single page, we cannot directly use the media/set in block Mage_adminhtml_block_media_uploader Uploader.phtml template is included because the media/uploader.phtml template contains a JS file that introduces the Flex uploader plugin dependency:  <?php echo $this->helper (' Adminhtml/js ')->includescript (' Lib/flex.js ')? ><?php echo $this->helper (' Adminhtml/js ') Includescript (' maGe/adminhtml/flexuploader.js ')? ><?php echo $this->helper (' Adminhtml/js ')->includescript (' lib/ Fabridge.js ')?>  when multiple Flex uploader plugins are used on the same page, these three JS are repeated multiple times, and errors occur in the operation.   The solution is to set the phtml module of the Mage_adminhtml_block_media_uploader sub-block in the foreground's custom block class to remove the JS-introduced code, like this in Block _preparelayout () The custom phtml template:  $this->getchild (' uploader ')->settemplate (' Custom/uploader.phtml ') is specified in the uploader method for the child block GetConfig ()   Finally, the _preparelayout () method in tabs block uniformly references the Flex uploader plugin-dependent JS file:  protected Function _ Preparelayout () {   //Flash multi-File Upload plugin Flex uploader    $this->getlayout ()->getblock (' head ')- >addjs (' lib/flex.js ');    $this->getlayout ()->getblock (' head ')->addjs (' mage/adminhtml/ Flexuploader.js ');    $this->getlayout ()->getblock (' head ')->addjs (' Lib/fabridge.js ');    return Parent::_preparelayout ();}   As above is about Magento multi-file upload function to achieve the solution, I hope to see you have help!

Implement Magento Multi-File upload Code feature development

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.