How To Upload Images Through Ajax In Prestashop

In this tutorial I will show you how to upload images through ajax in prestashop, this is not hard to achive you have to take few things in account in order to make this functionality to work. I posted a tutorial about how to save data through ajax in prestashop you can check it if you want to see the full tutorial about how to save your form data in a variable and send it to prestashop controller. Today I will try to show you how to upload an image to the server using few lines of jquery (ajax) and a php function to handle the upload.

For this tutorial we will use the following html:

<form action="your controller url">
  <input type="file" id="input_file" name="input_file">
</form>

As you can see there is no submit button in this form because we won't use it, we will create a change event on input file and every time when a new file is added to the input we will know and send the file to the prestashop controller. To this we will use the following jquery code:

jQuery('body').on('change', '#input_file', function(){
    var file = this.files[0],
      formData = new FormData(),
      link = jQuery(this).closest('form').attr('action'),
      element = jQuery(this);
      formData.append('uploadFiles', '1');
      formData.append('file', file);
      doUpload(formData, link, element);
  });

The above function will check if any change occur at our input, once a new file is dropped we will call doUpload() function through which we send the file to our controller. I append the uploadeFiles parameter to the formData to check in my controller if the right form was submitted, you will see a little below where I will add the code from controller.

var doUpload = function($file, $link, $element){
  jQuery.ajax({ 
    type:"POST",
    url:$link,
    data:$file,
    contentType: false,
    processData:false,
    success:function(result){
      var data = jQuery.parseJSON(result);
      if(data.success){
        console.log(data.success);
      }else if(data.error){
        alert(data.error);
      }
    },
    error:function(error){
      
    }
  });
}

In the above function is very important to set contentType and processData to false because in some cases the ajax won't work at all, setting them to false will make the ajax work in the right way. In success function we check what response come back from the controller and we will know what to do next. 

Now, in the backend we need to make functions to check when form is submitted and a new function which will handle the upload and the success and error messages which will be send back to the client. First we check if the form is submitted using the following code:

if(Tools::isSubmit('uploadFiles')){
  $file = $this->makeUpload($_FILES['file']);
  if(array_key_exists('success', $file)){
    echo json_encode(array('success' => 'done', 'filepath' => $file['filepath'], 'filename' => $file['filename']));
    exit();
  }else{
    echo json_encode(array('error' => $file));
    exit();
  }
}

If our form is submitted we send the file to makeUpload(), and then check if the array contain the key success if not that's mean an error occured and we will send the right message to the client. The makeUpload function looks like the following:

public function makeUpload($file){
    if(!empty($file)){	 
      $file_name = $file['name'];
      $rand_number = rand(0, 900);
      $temp = $file['tmp_name'];
      if ($error = ImageManager::validateUpload($file)) {
        return $error;
      } else {
        		$ext = substr($file_name, strrpos($file_name, '.') + 1);
        $file_name = substr($file_name,0,strrpos($file_name,'.'));
            	$file_name = $file_name.'.'.$ext; 
        if (!file_exists(_PS_MODULE_DIR_.'dashboard'.DIRECTORY_SEPARATOR.'files')) {
            mkdir(_PS_MODULE_DIR_.'dashboard'.DIRECTORY_SEPARATOR.'files', 0777, true);
        }
        if (!move_uploaded_file($temp, _PS_MODULE_DIR_.'homepage'.DIRECTORY_SEPARATOR.'files'.DIRECTORY_SEPARATOR.$file_name)) {
          return $this->displayError($this->trans('An error occurred while attempting to upload the file.', array(), 'Admin.Notifications.Error'));
        }
        return array('success' => true, 'filepath' => $this->base_path().'/modules/homepage/files/'.$file_name, 'filename' => $file_name);
      }
    }
  }

First check if the $file variable is not empty then we add the details needed to upload the file. You have to change the path for upload folder because in this example I used my own path. After you add all these functions everything should work great. This is one of the methods by which you can upload image through ajax in prestashop. In the following tutorial I showed you how to get file from input type file you can check it if you want.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x