Onepage Checkout – Add File Upload Field to any step

In this tutorial we are going to see how to add a file upload field to any of the magento checkout steps.

Adding file upload is a bit tricky in onepage checkout since all steps use ajax to save data. I am going to use jquery based ajax upload tool : Uplodify to setup the file uploading.
In the current module i have added the file upload field to billing step and payment method setup but following the same logic field can be added to any step. In the payment method section the file upload field is added to the purchase order payment method. Here are screenshot of the module

Admin Order View

Admin Order View

My Account Order View

My Account Order View

Onepage Checkout Billing Step

Onepage Checkout Billing Step

Onepage Checkout Payment Step

Onepage Checkout Payment Step

Attached is the source code of the module developed
[dm]28[/dm]
Lets see step by step explanation of the module source.

Step1: Add File Upload

First i have created a module name Excellence_File. The first step is to add the file upload field to the checkout billing step. For this first we need to override, the default checkout/onepage/billing.phtml file and put in our custom module. To this the following code is added to the layout xml of the module.

<checkout_onepage_index>
    	<reference name='head'>
    		<action method="addItem"><type>skin_js</type><name>uploadify/jquery-1.4.2.min.js</name></action>
    		<action method="addItem"><type>skin_js</type><name>uploadify/noconflict.js</name></action>
    		<action method="addItem"><type>skin_js</type><name>uploadify/jquery.uploadify.v2.1.4.js</name></action>
    		<action method="addItem"><type>skin_js</type><name>uploadify/swfobject.js</name></action>
    	</reference>
    	<reference name='checkout.onepage.billing'>
    		<action method='setTemplate'><template>file/checkout/onepage/billing.phtml</template></action>
    	</reference>
    </checkout_onepage_index>

As you can see in the above code the relevant uploadify java script files have been added to the checkout and the default billing.phtml file has been override to file/checkout/onepage/billing.phtml. In the new billing.phtml we add the upload field. Below code is added where you want to show the file upload field.

<ul class="form-list">
    	<li>
    		<label class="required"><em>*</em><?php echo $this->__('Please Upload Your Address Proof: ') ?><span id='file_upload_text'></span></label>
	        <div class="input-box">
				<input id="file_upload" type="file" name="file_upload" />
			</div>
			<input id="file_upload_path" type="hidden" name="file_upload_path" class='required-entry'  />
			<input type="hidden" value='billing_file' name="file_upload_type" class='required-entry'  />
    	</li>
    </ul>

Here important thing to notice is we have added two fields with name file_upload_path and file_upload_type which we will use later.
Next we need to initialize the uploadify java script

<script type="text/javascript">
// <![CDATA[
jQuery(document).ready(function() {
	jQuery('#file_upload').uploadify({
    'uploader'  : '<?php echo $this->getSkinUrl('uploadify/uploadify.swf') ?>',
    'cancelImg' : '<?php echo $this->getSkinUrl('uploadify/cancel.png') ?>',
    'script'    : '<?php echo $this->getUrl('file/index/upload') ?>',
    'auto'       : true,
    'fileDataName' : 'file',
    'fileExt'     : '*.jpg;*.gif;*.png',
    'fileDesc'    : 'Image Files',
    'onComplete' : function(event, ID, fileObj, response, data){
    	jQuery('#file_upload_path').val(response);
    	jQuery('#file_upload_text').html('File Uploaded: '+fileObj.name);
     }
    
  });
});
// ]]>
</script>

After doing the above step the file upload field should start showing up in the billing checkout step. Similarly we can add the upload field to the payment step as well, for details please check the source code.

Step2: Saving File

Now we need to create a controller where the actual file upload takes place. In the uploadify script we have set

    'script'    : '<?php echo $this->getUrl('file/index/upload') ?>'

as the file uploading url. So we next create the IndexController and uploadAction() as shown.

<?php
require_once 'Mage/Checkout/controllers/OnepageController.php';
class Excellence_File_IndexController extends Mage_Checkout_OnepageController
{
	public function uploadAction()
	{
		Mage::log($_FILES);
		if ($data = $this->getRequest()->getPost()) {
				
			$type = 'file';
			if(isset($_FILES[$type]['name']) && $_FILES[$type]['name'] != '') {
				try {
					$uploader = new Varien_File_Uploader($type);
					//$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
					$uploader->setAllowRenameFiles(true);
					$uploader->setFilesDispersion(true);
					$path = Mage::getBaseDir('media') . DS . 'uploads' . DS;
					$uploader->save($path, $_FILES[$type]['name'] );
					$filename = $uploader->getUploadedFileName();
						
				} catch (Exception $e) {
				}

			}
			echo $filename;
		}
	}
}

Here we are only using magento uploader to save file to hard disk and return the file path.

Step3: Saving File To Database

Now we need to save the file path of the uploaded file to the database. For each quote object, we need to save the file path and file type. Here file type is the custom input type added by me and not the media type. This file type field has been added just to identify later which file was uploaded in which step. To save the file to database, i have added an event observer for sales quote save after.

<sales_quote_save_after>
    			<observers>
    				<sales_quote_save_after>
    					<type>singleton</type>
	                    <class>Excellence_File_Model_Observer</class> <!-- Over Model Class -->
	                    <method>saveQuoteAfter</method> <!-- name of function -->
    				</sales_quote_save_after>
    			</observers>
    		</sales_quote_save_after>

and the code in the saveQuoteAfter() function is

public function saveQuoteAfter($evt){
		$quote = $evt->getQuote();

		$post = Mage::app()->getRequest()->getPost();

		if(isset($post['file_upload_path'])){
			$quote_id = $quote->getId();
			$filename = $post['file_upload_path'];
			$type = $post['file_upload_type'];
			Mage::log($quote_id.'xx'.$filename);
			Mage::getModel('file/file')->saveFile($quote_id,$filename,$type);
		}

	}

Here first we check if file_upload_path variable is found in $_POST. If it’s found then it gets saved to a custom database table created. The code to create the custom database is

DROP TABLE IF EXISTS {$this->getTable('quote_file')};
CREATE TABLE {$this->getTable('quote_file')} (
  `id` int(11) unsigned NOT NULL auto_increment,
  `quote_id` varchar(255) NOT NULL default '',
  `filename` varchar(255) NOT NULL default '',
  `type`  varchar(255) NOT NULL default '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Step4: Transfer Files To Order

This is the final step where we need to associate the files uploaded to the order placed. For this i have added observer to the checkout_submit_all_after event.

<checkout_submit_all_after>
    			<observers>
                   <save_after> <!-- Any Unique Identifier -->
	                    <type>singleton</type>
	                    <class>Excellence_File_Model_Observer</class> <!-- Over Model Class -->
	                    <method>placeOrderAfter</method> <!-- name of function -->
                   </save_after>
		        </observers>
    		</checkout_submit_all_after>

and in the placeOrderAfter() function add the code

public function placeOrderAfter($evt)
	{
		$order = $evt->getOrder();
		$quote = $evt->getQuote();

		$quote_id = $quote->getId();
		$order_id = $order->getId();

		$collection = Mage::getModel('file/file')->getCollection();
		$collection->addFieldToFilter('quote_id',$quote_id);

		Mage::log('Observer Place Order After Quote ID:' . $quote_id);

		foreach($collection as $object){
			Mage::getModel('file/order')->saveFile($order_id,$object->getFilename(),$object->getType());
			$object->delete();
		}
// 		Mage::getModel('file/file')->resetUniqId();
	}

What this does is simply read all files from the quote table and add it a new order table. The structure of the order table is

DROP TABLE IF EXISTS {$this->getTable('order_file')};
CREATE TABLE {$this->getTable('order_file')} (
  `id` int(11) unsigned NOT NULL auto_increment,
  `order_id` varchar(255) NOT NULL default '',
  `filename` varchar(255) NOT NULL default '',
  `type`  varchar(255) NOT NULL default '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This is a basic explanation of the module there are many more files in the source code attached. This module can be extended to support multiple file uploads as well.
  • Dejan

    I can’t install on Magento 1.6.1 :/
    Any advice?

    • Manish Prakash

      Whats the problem your facing

      • Dejan

        I am download “Checkout File Upload” and put the files in a specific
        folders, but no change in  FrontEnd when i ordering from shopcart!

        • Manish Prakash

          i have updated the module. can you download and re-install it?

  • Dejan

    I am download “Checkout File Upload” and put the files in a specific folders, but no change in  FrontEnd when i ordering from shopcart!

  • Where can I find the module once it is installed ? It is active in System>Configuration>Advanced, but I can’t see where configure it in the admin panel. Thanks !

    • I am really interrested in this module, it would be very helpful to me, but after hours I just can’t make it work. I pasted the design and skin files in my customized template folder, but nothing happens neither in admin panel, nor in frontend. Please I really need your advice about that ! Thank you

      • Manish Prakash

        Which version are you using?

        • I was using magento 1.6.0.0. I just updated my version but couldn’t update Mage_Core_Modules because of find_feed, so I still have 1.6.0.0 version…

          •  Ok I just managed to upgrade my version, so I’m on 1.6.2 now. I send you an admin access and a FTP access. Thank you for your help.

          • Manish Prakash

            Where have you sent your ftp access? Please send it to my email id

          •  I have sent it to contact@excellencetechnologies.in because I didn’t find where contact you elsewhere.

          • Manish Prakash

            i have updated the module. can you download and re-install it?

      • Manish Prakash

        Can you send me your site ftp detail through mail, I will try to debug and see.

  • I re-installed it just uploading the files in my FTP. Should I do something else ? I can’t see anywhere the field “file upload”. Thank you

    •  Ok I finally succed. In the file app/etc/modules/Excellence_File.xml, active param was “false” although the config>system>advanced checkbox for Excellence_File was checked. Now I have the “Please Upload Your Address Proof:” on billing step. Can I manage this field in admin panel ? If so, where ?
      Thank you very much again for your word !

  • Hello Manish,

    With this module, can i add the upload function after customer pays?. I want customers to pay before uploading files.

    Thanks,

    • Manish Prakash

      No in this module file’s are uploaded before payment

  • Tyler

    Hey mate, great script you have here. I’m wondering if I could have this implemented in the product view (most of my products will have this) so that people can add several files at once, and then I can download them from the admin area?

    • Manish Prakash

      In product page you can do it directly through custom options in magento admin .

      • PragM

        Hi,  can you explain in detail how to do that throught magento admin ? I am looking for a tutorial to add a file upload field in product page, but i can’t find anything on Web exept this great article of you! Thanks for your help. 

        • Manish Prakash

          If you want file uploading in a product page, it is very simple. You need to do it through ‘Custom Options’ in edit product page in admin.

          • PragM

            Thanks a lot!

  • Sazon

    I don’t know English very well, sorry.It don’t work on magento 1.3.3.0( I install module, refresh cashe and go to the form for order and see, that it’s form don’t work (in attachment image). Then I delete this module, refresh cash – all work.Please help me

    • Manish Prakash

      Magento 1.3.3 is a very old version, I am not sure if module will work on it.

      • Sazon

        can you tell me a small hint? (what could be the reason, perhaps, you suspect) I mean the code, it is likely that I’ll be able to fix

        • Manish Prakash

          The checkout system code in 1.3.3 was entirely different, so it won’t be a small fix

  • Bharanidharan K

    i have a problem,

    i create news and event modules and i set as menu links every thing is fine, but there is a loading time difference between other menus and my own module menus, other menu links are loaded very fast when compare to my own module menu.,

    can you help me

  • Info

    A great solution and 100% what I was looking for. Good work!
    One question: I try to change the text on the button SELECT FILES. This is a Flash-Button located within the skin-folder. But when I change the uploadify.swf (the .fla is also located in within the skin folder), the upload doesn´t work anymore. Can anybody tell me, how to change the wording? All i need is the word UPLOAD within the button. Thank you and have a nice weekend, Oliver

  • Hi,first of all thanks for your blog it helps me a lot!!,I want to create a module for pdf functionality,which provide the option on product view page to download the product as pdf with all fields.can you guide me please.

  • VipinSahu

    nice information. do you have any information regarding how to add file uploader in magento custom options ?

  • hi, very goog this module.
    say me. how to upload more files??
    tks

  • Hi, do this work with magento 1.7?
    how can in installl it? just by uploading file with ftp or with magento connect?

  • brad

    i cant seem to get this working ive uploaded and it is appearing in the modules as enabled but it doesnt seem to active in the front end im using 1.7.2

  • Manish Prakash

    Hi smitha,
    Since required-entry class is added to make it a required value. So you might be continuing with the process without uploading any file. You need to upload file as it is a required field.

    • Bhupendra

      This module work excellent for Check / Money order but its not work for Paypal Express Checkout.
      So please help….

  • I can’t log in to download module, please help me I really need this code, it is very helpful but I’m affraid the written is incomplete. Thanks so much

  • Manish Prakash

    Well, that too is possible, when i’ll get some time, i’ll try to write blog on this too.

  • Salman Khan

    unable to upload files using mobile or android device

    • Bhadresh

      because its swf file u have change jquery

  • Rupesh Yadav

    Thanks it worked like charm…..

  • Bhadresh

    excellent excellent excellent

    I have to developed multiple File upload Maegnto 1.8

  • Guest

    Excellent module i have developed Multiple File Upload Each Product
    using this module very helpful

    • Herman

      Could you provide the code for

  • Bhadresh

    Excellent excellent excellent
    I have to developed multiple File upload Maegnto 1.8

    using this module very helpful

    • Lee

      This looks great!
      Would you be willing to share the code for this?

      • Bhadresh

        yes

    • khan88

      hi Bhadresh, can u give me an idea or share the code, how to modify this module for file upload in cart page like above figure.

  • Bhadresh Shiroya

    i have to move upload Section Shopping Cart Each Product Upload images and file sucessfully and Database quote_id also quote_file table after i have login then upload file doesn’t show , i have check db i see the quote_id different ..my problem is non login customer how to handle quote_id in magento

  • Warren Sanejo

    Hi I have downloaded the file and installed it. the front end seems to work but i cannot find the uploaded files block from the sales order view . can you help me which file to look at?

  • Bhupendra

    Hi, there… excellent module.
    This module work excellent for Check / Money order but its not work for Paypal Express Checkout.
    So please help….

  • nexerices

    Hello Manish
    This Extention is very usefull ..
    i have a question how to upload multiple files and how to use this mudule on checkout/cart page ?
    i want like this way .

  • Lee

    Thanks for this, very helpful!

  • ravi

    I want to add custom shipping method with text box. This textbox will be a shipping method name.

  • Bhadresh

    I have to developed multiple File upload Maegnto 1.8 using your Tutorial
    but MAC OS do not works
    because it using Flash
    Can I Give me another solution ?

  • Davi Reinoldo

    this module works with onestep checkout?
    how can I put it to works with them?…

  • srinu

    Hi Manish, When i installed this module, its working . later on the button is not displaying and in the console display none is showing. Please check the attachment image. Thank you

  • Srinivas G

    Hi , I installed this module it was working good in all browsers but i was getting some problem in Mozilla Firefox and the button not getting displayed in mozilla firefox. Please Help

  • Srinivas G

    Hi , I installed this module it was working good in all browsers but i
    was getting some problem in Mozilla Firefox and the button not getting
    displayed in mozilla firefox. Please Help

  • Michael Erpunkt

    Hi! In the beginning of the article, where one can download the module source, it says:

    “Error… Unable to load download template. Search single-download-template.tpl in your plugin folder!”

    Can you check this please? I’d love to use this module in one of my projects.

  • Madhav Sharma

    Hi,

    Can any one send me the downloadable source code for the above module for magneto 1.8.1, i am not able to find any attachment.

    Thanks

  • Rajesh

    where i download this Checkout File Upload extension?

  • Naval Kishore kandpal

    I didn’t find the attached source code of the module. Please let me know how to download the module.

  • Prince Patel

    hello,
    when i use this custom module but after setup this module, the state field has not showing in billing address step, so please give me some solution ASAP,

    thankx

  • Seth Zweig

    Hello Manish, this looks like a great module, exactly what I need. However, I cannot download the module anywhere on this page. Do you have the souce code available for download? Also, do you know if this works on 1.9x?

    thanks!

    • Marco B

      Hi Seth, you received information on where to download the souce code?

  • Gabriel Grando

    @manishiitg:disqus I am trying to use this module but I’m having a problem with this part of the code

    .

    The upload button shows up but it seems not being able to acquire the file path, so it doens’t upload any file nor let me continue in the checkout process, giving me “This is required field” error.
    Do you have any suggestion? Magento 1.9.3
    Thanks