How to Upload files on Different page of PrestaShop - Top Programming Questions and Answers

Posted On: Sep 14, 2018

Categories: Shopping Carts & Platforms

Tags: prestashop , module , file upload ,

PrestaShop is most simple shopping cart that suits for small sized businesses. If you are looking to open a new shop, PrestaShop should be at your first option. The reason is that it is fully open source and one can modify it according to this own choice.

The topic that we selected today for questions answers session is basically an advance functionality of PrestaShop and that is File upload option at different pages of PrestaShop. Being a merchant, sometimes you need to get some files from customers in the form of PDF, excel, video, MP3, JPEG or any of the other file format. It is not better to have third party clouding servers to get files. Why not get it done through your own shop server? Similarly, sometimes you need to send a file to your customers, it can be done through PrestaShop itself and therefore cutting the need of external services.

The today’s post targets the same thing. While using this feature, people gets some errors or bugs and they look for a solution for them. We have tried today to give every possible solution of such issues. So given here Top Programming Questions and Answers about File Upload Option in PrestaShop;

Question No. 1: Hi, I want to disable the upload option at the contact form so that no one can send me the files through this option?

Answer: You can deactivate this option from the back office. Go to customers>Customer Services. Where you can make the option on or off as per your choice.

Question No. 2: Hi, I want to create an input field on the customer registration form. Through this fields, visitors have to upload a file containing the proof that he has right to access the store. I want to check this proof and then allow his registration. How it is possible?

Answer: You need to modify the registration form. You can access the registration form through ./themes/YOUR-THEME/authentication.tpl. Right after the birth day field around line 130, you have to add this;

<divclass="form-group">

    <labelfor="fileUpload">{l s='Select file'} <sup>*</sup></label>

    <inputtype="hidden"name="MAX_FILE_SIZE"value="2000000"/>

    <inputtype="file"class="required form-control"id="fileUpload"name="fileUpload"/>

</div>

You can add the filed in customer class  and Controllers(AdminCustomersController.php, AuthController.php, Customer.php).

First of all, name a field ‘fileupload’ through which you are declaring and creating the field.

Let's run this statement on SQL to create the field in the customer table to store the filename.

ALTERTABLE`ps_customer`ADD`fileUpload` VARCHAR(100)NOTNULL;

In ./classes/Customer.php around line ~30 we'll find the declared variables. Add the new one like this:

  1. classCustomerCoreextendsObjectModel
  2. {
  3. public $id;
  4. public $fileUpload;
  5. public $id_shop;
  6. ...

then in line ~192 add the new field like this:

  1. 'date_add'=> array('type'=>self::TYPE_DATE,'validate'=>'isDate','copy_post'=>false),
  2. 'date_upd'=> array('type'=>self::TYPE_DATE,'validate'=>'isDate','copy_post'=>false),
  3. 'fileUpload'=> array('type'=>self::TYPE_STRING,'validate'=>'isGenericName'),
  4. ),

Now, inside ./controllers/front/AuthController.php around line ~379 we prepare the information:

  1. // Preparing customer
  2. $customer =newCustomer();
  3. $lastnameAddress =Tools::getValue('lastname');
  4. $firstnameAddress =Tools::getValue('firstname');
  5. $_POST['lastname']=Tools::getValue('customer_lastname', $lastnameAddress);
  6. $_POST['firstname']=Tools::getValue('customer_firstname', $firstnameAddress);
  7.  
  8. // Add this line
  9. $fileUpload =Tools::getValue('fileUpload');
  10.  
  11. ... 

around line ~423 you will find the birthday validation, so you have to make the validation field.

  1. $customer->firstname =Tools::ucwords($customer->firstname);
  2. $customer->birthday =(empty($_POST['years'])?'':(int)Tools::getValue('years').'-'.(int)Tools::getValue('months').'-'.(int)Tools::getValue('days'));
  3. if(!Validate::isBirthDate($customer->birthday))
  4.     $this->errors[]=Tools::displayError('Invalid date of birth.');
  5.  
  6. // Add this code...
  7. //$customer->fileUpload = 'N/A';
  8. // If you want the uploader as OPTIONAL, remove the comment of the line above.
  9. $file = $_FILES['fileUpload'];
  10. $allowed = array('txt','rtf','doc','docx','pdf','png','jpeg','gif','jpg');
  11. $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
  12. if( file_exists($file['tmp_name'])&& in_array($extension, $allowed))
  13. {
  14. $filename = uniqid()."-".basename($file['name']);
  15. $filename = str_replace(' ','-', $filename);
  16. $filename = strtolower($filename);
  17. $filename = filter_var($filename, FILTER_SANITIZE_STRING);
  18.  
  19. $file['name']= $filename;
  20.  
  21. $uploader =newUploaderCore();
  22. $uploader->upload($file);
  23.  
  24. $customer->fileUpload = $filename;
  25. }

 

The same way, in the line ~552, leaving it like this:

  1. $customer->birthday =(empty($_POST['years'])?'':(int)Tools::getValue('years').'-'.(int)Tools::getValue('months').'-'.(int)Tools::getValue('days'));
  2. if(!Validate::isBirthDate($customer->birthday))
  3.                $this->errors[]=Tools::displayError('Invalid date of birth');
  4.  
  5. // Add this code...
  6. //$customer->fileUpload = 'N/A';
  7. // If you want the uploader as OPTIONAL, remove the comment of the line above.
  8. $file = $_FILES['fileUpload'];
  9. $allowed = array('txt','rtf','doc','docx','pdf','png','jpeg','gif','jpg');
  10. $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
  11. if( file_exists($file['tmp_name'])&& in_array($extension, $allowed))
  12. {
  13. $filename = uniqid()."-".basename($file['name']);
  14. $filename = str_replace(' ','-', $filename);
  15. $filename = strtolower($filename);
  16. $filename = filter_var($filename, FILTER_SANITIZE_STRING);
  17.  
  18. $file['name']= $filename;
  19.  
  20. $uploader =newUploaderCore();
  21. $uploader->upload($file);
  22.  
  23. $customer->fileUpload = $filename;

This way the files will be uploaded in the ./upload/ folder, if you want to specify another subfolder just insert the path in $uploader->upload('my-path/'.$_FILES['fileUpload']);

 

To add the input fields in the registration form open ./themes/YOUR-THEME/authentication.tpl around ~182 and ~509 right after the birthday fields.

  1. <divclass="form-group">
  2.     <labelfor="fileUpload">{l s='Select file'} <sup>*</sup></label>
  3.     <inputtype="hidden"name="MAX_FILE_SIZE"value="2000000"/>
  4.     <inputtype="file"class="required form-control"id="fileUpload"name="fileUpload"/>
  5. </div>

Don't forget to configure the form to send multimedia information on every <form> tags like the following code: (depends on theme)

  1. <formmethod="post"id="create-account_form" ... enctype="multipart/form-data">

To show the filename in the client list open ./controllers/admin/AdminCustomersController.php around line ~159 and add:

  1. 'connect'=> array(
  2.         'title'=> $this->l('Last visit'),
  3.         'type'=>'datetime',
  4.         'search'=>false,
  5.         'havingFilter'=>true
  6. ),
  7. 'fileUpload'=> array(
  8.         'title'=> $this->l('Uploaded File'),
  9.         'type'=>'text',
  10.         'search'=>true,
  11.         'havingFilter'=>true
  12. )
  13. ));

In the same file, around ~821:

  1. // Connections
  2. 'connections'=> $connections,
  3. // Uploaded File
  4. 'fileUpload'=> $fileUpload,
  5. // Referrers
  6. 'referrers'=> $referrers,
  7. 'show_toolbar'=>true

Clean the cache after updating the files.

If you want to show the files inside the Customer View you need to modify ./admin/themes/default/template/controllers/customers/helpers/view/view.tpl

put this code right after the $customer->birthday validation at lines ~550 and ~420 to run the uploader in AuthController.php

if(isset($_FILES['fileUpload']['name'])&&!empty($_FILES['fileUpload']['name'])&&!empty($_FILES['fileUpload']['tmp_name']))

{

      $extension = array('.txt','.rtf','.doc','.docx','.pdf','.png','.jpeg','.gif','.jpg');

      $filename = uniqid().basename($_FILES['fileUpload']['name']);

      $filename = str_replace(' ','-', $filename);

      $filename = strtolower($filename);

      $filename = filter_var($filename, FILTER_SANITIZE_STRING);

 

      $_FILES['fileUpload']['name']= $filename;

 

      $uploader =newUploaderCore();

      $uploader->upload($_FILES['fileUpload']);

 

      $customer->fileUpload = $filename;

}

Question No. 3: Hi, I want that the order information will be printed on a single page and I should have option to select which part should appear on print page and which material not. By default, it prints on 3 pages which is a bit useless.

Answer: Go to override.css in /admin/themes/default/css/override.css from where you can change the print style as needed. 

@media print {

 p {text-indent: 10%}

}

You need to adjest with css action "display:none" with Paypal tab and other tab.

Question No. 4: I am using PrestaShop 1.6 and I want make use of import.csv.  We have imported the images and text and set the upload file option to 1. Now guide me to how to upload and attach a PDF file as a data sheet with products.

Answer: So in the AdminImportController.php, add those two lines in the  fields list for products import (case $this->entities[$this->l('Products')])

'delete_existing_attachments'=> array('label'=> $this->l('Delete existing attachments (0 = No, 1 = Yes)')),

'attachment'=> array('label'=> $this->l('attachment')),

Then at the end of the function productImport(), after those lines:

else{

                        StockAvailable::setQuantity((int)$product->id,0,(int)$product->quantity,(int)$this->context->shop->id);

                    }

                };

add this:

 // Attachment files import

                

        //delete existing attachments if "delete_existing_attachments" is set to 1

                if(isset($product->delete_existing_attachments))

                    if((bool)$product->delete_existing_attachments)

                        $product->deleteAttachments();

                

                

                $attachments = get_object_vars($product);

 

                if(isset($attachments['attachment'])&&!empty($attachments['attachment']))

                    foreach(explode($this->multiple_value_separator, $attachments['attachment'])as $single_attachment)

                    {

                    

                        $tab_attachment = explode('|', $single_attachment);

                        $attachment_filename = isset($tab_attachment[0])? $tab_attachment[0]:'';

                        $attachment_name = isset($tab_attachment[1])? trim($tab_attachment[1]): $attachment_filename ;

                        $attachment_description = isset($tab_attachment[2])? trim($tab_attachment[2]):'';

 

                        if(!empty($attachment_filename))

                        {

                            $id_attachment =(int)Attachment::addAttachmentImport($attachment_filename, $attachment_name, $attachment_description);

 

                            Attachment::addAttchmentProductImport($product->id, $id_attachment);

                            Product::updateCacheAttachment($product->id);

                        }

                    

                    }

 

 In the attachment class file (classes/Attachment.php)

add at the end those two functions:

          publicstaticfunction addAttachmentImport($filename, $name, $description)

    {

            $attachment =newAttachment();

            

            $languages =Language::getLanguages();

            foreach($languages as $language)

            $attachment->name[$language['id_lang']]= strval($name);

            $attachment->description[$language['id_lang']]= $description;

 

            $attachment->file = sha1($filename);

            $attachment->file_name = $filename;

            

            $path_file = _PS_DOWNLOAD_DIR_.$filename;

            $attachment->file_size = filesize($path_file);

 

            $finfo = finfo_open(FILEINFO_MIME_TYPE);

            $attachment->mime = finfo_file($finfo, $path_file);

 

            $attachment->addAttachment();

 

            return(int)$attachment->id;        

    }

    

    

    publicstaticfunction addAttchmentProductImport($id_product, $id_attachment)

    {

        returnDb::getInstance()->execute('

            INSERT INTO `'._DB_PREFIX_.'product_attachment` (`id_attachment`, `id_product`)

            VALUES ('.(int)$id_attachment.', '.(int)$id_product.')

        ');

 

    }

delete the cache file: /cache/class_index.php

 

You must put your files in the /Download folder. 

In your cvs file, the "attachment" column could contain this:
myfile1.doc|Name of my file 

Or if you want to attach several files to one product:

myfile1.doc|Name of my file%myfile2.pdf| Name of my file

Question No. 5: Is there a way to bound the visitors to upload a company document on registration page. While searching on internet, I found such uploading modules there which allows uploading on order, product and cart page but how to do it on registration?

Answer: Sadly, there is already available module for this purpose. So you need to do a core modification or writing your own module. However, if you are not code expert, contact some module development company.

Note: These questions are answered by top community developers and do not reflect FMEModules.