Use Mage_Uploader in custom form in store frontend
-
05-10-2020 - |
Question
Magento 1.9.3 (also: 1.x with security patch SUPEE-8788) introduced the Mage_Uploader
module, a new file upload widget without Flash. The core only uses it in the admin area (product images, CMS), but I would like to have it on a custom form in the frontend too, to allow multiple file uploads.
What do I need to do to make it available in the frontend?
Solution
I managed to use it with the following steps:
- Copy
app/design/adminhtml/default/default/template/media/uploader.phtml
toapp/design/frontend/base/default/template/media/uploader.phtml
Add the following JavaScript files via layout XML:
<reference name="head"> <action method="addJs"> <name>lib/uploader/flow.min.js</name> </action> <action method="addJs"> <name>lib/uploader/fusty-flow.js</name> </action> <action method="addJs"> <name>lib/uploader/fusty-flow-factory.js</name> </action> <action method="addJs"> <name>mage/adminhtml/uploader/instance.js</name> </action> </reference>
Include the
Mage_Uploader
translations in the frontend (in my modulesconfig.xml
):<frontend> <translate> <modules> <Mage_Uploader> <files> <default>Mage_Uploader.csv</default> </files> </Mage_Uploader> </modules> </translate> </frontend>
Add the relevant CSS from the admin theme:
.uploader .buttons { margin-bottom: 10px; } .uploader .clear:after { display:block; clear:both; content:"."; font-size:0; line-height:0; height:0; overflow:hidden; } .uploader .file-row { width:600px; padding:0.5em 0.6em; margin:0.5em 0.6em; border:1px solid #ccc; background-color:#f9f9f9; /*vertical-align:middle;*/ } .uploader .file-row-narrow { width: auto; margin: 0 0 2px 40px; } .uploader .file-row .file-info { float:left; } .uploader .file-row-info { margin: 0 0 0 10px; } .uploader .file-row-info .file-info-name { font-weight:bold; } .uploader .file-row .progress-text { float:right; font-weight:bold; } .uploader .file-row .delete-button { float:right; } .uploader .progress { border:1px solid #f0e6b7; background-color:#feffcc; } .uploader .error { border:1px solid #aa1717; background-color:#ffe6de; } .uploader .error .progress-text { padding-right:10px; } .uploader .complete { border:1px solid #90c898; background-color:#e5ffed; }
Include the uploader in my form with a block method like this:
public function getUploaderHtml() { $uploader = $this->getLayout()->createBlock('uploader/multiple'); $uploader->getUploaderConfig()->setTarget($this->getUrl('my/upload/controller')); return $uploader->toHtml() }
write a controller (as specified in
setTarget()
above) which handles the file upload. It should return the result ofVarien_File_Uploader::save()
as JSON or in case of error:json_encode(['error' => 'error message', 'error_code' => 123]);