Showing posts with label Upload. Show all posts
Showing posts with label Upload. Show all posts

Thursday 5 September 2019

How to upload image file with ajax

jQuery("form#add-group-form").submit(function(e){
        e.preventDefault();
        var formData = new FormData(jQuery(this)[0]);
       
        jQuery.ajax({
            type:"POST",
            url:jQuery(this).attr("action"),
            data:formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function(response){
                alert(response);
            }
        });
    });

Wednesday 27 December 2017

How to upload image / file in magento


<input type="file" name="image">

Select path of media directory

$path = Mage::getBaseDir() . DS . 'media' . DS . 'customerimages' . DS;
$imagename = $this->uploadImageFile($_FILES, $path);

Create functions

function uploadImageFile($filedata, $path){
   
    if(isset($filedata['image']) && $filedata['image']['error'] == 0){
        try{
           
            $uploader = new Varien_File_Uploader('image');
            $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
            $uploader->setAllowRenameFiles(true);
           
            if(!is_dir($path)){
                mkdir($path, 0755, true);
            }
            $ext = pathinfo($filedata['image']['name'], PATHINFO_EXTENSION);
            $uploader->save($path, date('Ymd') . "_" . date('his') . '.' . $ext);
            $uploadFile = $uploader->getUploadedFileName();
            if($uploadFile){
                return $uploadFile;
            } else {
                return 'File not uploaded!';
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
    } else {
        return 'Please select image file!';
    }
}

Saturday 8 October 2016

How to upload products multiple images in codeigniter Gocart in admin panel

Open : gocart/views/admin/iframe/product_image_uploader.php

<?php include('header.php');?>
<script type="text/javascript">
 
<?php if( $this->input->post('submit') ):?>
$(window).ready(function(){
        $('#iframe_uploader', window.parent.document).height($('body').height()); });
<?php endif;?>
<?php if($file_name):?>
        parent.add_product_image('<?php echo json_encode($file_name);?>');
<?php endif;?>
 
</script>
<?php if (!empty($error)): ?>
    <div class="alert alert-error">
        <a class="close" data-dismiss="alert">×</a>
        <?php echo $error; ?>
    </div>
<?php endif; ?>
<div class="row-fluid">
    <div class="col-md-12">
        <?php echo form_open_multipart($this->config->item('admin_folder') . '/products/product_image_upload', 'class="form-inline "'); ?>
        <?php echo form_upload(array('name' => 'userfile[]', 'id' => 'userfile', 'class' => 'input-file', 'multiple'=>"true" )); ?>
        <input class="btn" name="submit" type="submit" value="<?php echo lang('upload'); ?>" />
        </form>
    </div>
</div>
<?php include('footer.php');


Open : gocart/controllers/admin/products.php

Update product_image_upload() function

function product_image_upload() {
        $data['file_name'] = false;
        $data['error'] = false;
        $config['allowed_types'] = 'gif|jpg|png';
        //$config['max_size'] = $this->config->item('size_limit');
        $config['upload_path'] = 'uploads/images/full';
        $config['encrypt_name'] = true;
        $config['remove_spaces'] = true;
        $this->load->library('upload', $config);
        $files = $_FILES;
     
        $cpt = count($_FILES['userfile']['name']);
        for($i=0; $i<$cpt; $i++)
        {
            $_FILES['userfile']['name']= $files['userfile']['name'][$i];
            $_FILES['userfile']['type']= $files['userfile']['type'][$i];
            $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
            $_FILES['userfile']['error']= $files['userfile']['error'][$i];
            $_FILES['userfile']['size']= $files['userfile']['size'][$i];

            //$this->upload->initialize($this->set_upload_options());
         
            if ($this->upload->do_upload()) {
                $upload_data = $this->upload->data();
             
                $this->load->library('image_lib');
                /*
                  I find that ImageMagick is more efficient that GD2 but not everyone has it
                  if your server has ImageMagick then you can change out the line
                  $config['image_library'] = 'gd2';
                  with
                  $config['library_path'] = '/usr/bin/convert'; //make sure you use the correct path to ImageMagic
                  $config['image_library'] = 'ImageMagick';
                 */
                //this is the larger image
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/images/full/' . $upload_data['file_name'];
                $config['new_image'] = 'uploads/images/medium/' . $upload_data['file_name'];
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 600;
                $config['height'] = 500;
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                //small image
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/images/medium/' . $upload_data['file_name'];
                $config['new_image'] = 'uploads/images/small/' . $upload_data['file_name'];
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 235;
                $config['height'] = 235;
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                //cropped thumbnail
                $config['image_library'] = 'gd2';
                $config['source_image'] = 'uploads/images/small/' . $upload_data['file_name'];
                $config['new_image'] = 'uploads/images/thumbnails/' . $upload_data['file_name'];
                $config['maintain_ratio'] = TRUE;
                $config['width'] = 150;
                $config['height'] = 150;
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $this->image_lib->clear();
                $data['file_name'][] = $upload_data['file_name'];
            }
        }
        if ($this->upload->display_errors() != '') {
            $data['error'] = $this->upload->display_errors();
        }
        $this->load->view($this->config->item('admin_folder') . '/iframe/product_image_uploader', $data);
    }


Open : gocart/views/admin/product_form.php

Update : add_product_image(data) function


function add_product_image(data) {
     
        var $images = $.parseJSON(data);
        $.each($images, function(i, image) {
            p = image.split('.');
            var photo = '<?php add_image("' + p[0] + '", "' + p[0] + '.' + p[1] + '", '
            ', '
            ', '
            ', base_url('
            uploads / images / thumbnails '));?>';
            $('#gc_photos').append(photo);
            $('#gc_photos').sortable('destroy');
            photos_sortable();
        });
    }

Tuesday 30 August 2016

How to Get / Upload / Delete / Update file in using SFTP / FTP in PHP, Codeigniter Library

PHP has ssh2 stream wrappers (disabled by default), so you can use sftp connections with any function that supports stream wrappers by using ssh2.sftp:// for protocol

Here is a small code on how to read the folder and download all files:

Controller.php

      $params = array('host' => $shopdata->ftphost, 'port' => 22);
            $this->load->library('sftpconnection', $params);
         
            $this->sftpconnection->login($shopdata->ftpuser, $shopdata->ftppass);
            //$this->sftpconnection->uploadFile("http://localhost/shopify/inventorymanagement/uploads/sku.csv", "/codetest/test.csv");
            //$result = $this->sftpconnection->scanFilesystem("/TEST/DESADV");
            $result = $this->sftpconnection->downloadFiles("$folder","/TEST/DESADV/");
            pre($result);
Create Library file : Sftpconnection.php

<?php
/*
  Sftp connection in PHP
  Created: Feb 18th, 2016
  Modified: Feb 18th, 2016
  Version: 1.0.1
  Auther : Jaydip Kanasagra
 */

//this function is just to make the code a little cleaner
class Sftpconnection {

    private $connection;
    private $sftp;

    public function __construct($config) {
        $host = $config['host'];
        $port = $config['port'];
        $this->connection = @ssh2_connect($host, $port);
        if (!$this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password) {
        if (!@ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
            "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (!$this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file) {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

        if (!$stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }

    public function receiveFile($remote_file, $local_file) {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (!$stream)
            throw new Exception("Could not open file: $remote_file");
        $contents = fread($stream, filesize("ssh2.sftp://$sftp$remote_file"));
        file_put_contents($local_file, $contents);
        @fclose($stream);
    }
 
    public function downloadFiles($local_dir, $remote_dir) {
        $sftp = $this->sftp;
        $dir = "ssh2.sftp://$sftp$remote_dir";
        $downloadedfiles = $files = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
     
        foreach ($files as $file)
        {
            $currentdir = $this->getCurrentdirfiles('uploads/ftpfiles/TEST/JAYDIP/');
            if(in_array($file, $currentdir)){
                continue;
            }
         
            echo "Copying file: $file<br>";
            if (!$remote = @fopen("ssh2.sftp://{$sftp}{$remote_dir}{$file}", 'r'))
            {
                echo "Unable to open remote file: $file\n";
                continue;
            }

            if (!$local = @fopen($local_dir . $file, 'w'))
            {
                echo "Unable to create local file: $file\n";
                continue;
            }

            $read = 0;
            $filesize = filesize("ssh2.sftp://{$sftp}/{$remote_dir}{$file}");
            while ($read < $filesize && ($buffer = fread($remote, $filesize - $read)))
            {
                $read += strlen($buffer);
                if (fwrite($local, $buffer) === FALSE)
                {
                    echo "Unable to write to local file: $file\n";
                    break;
                }
            }
            $downloadedfiles[] = $file;
            fclose($local);
            fclose($remote);
        }

        return $downloadedfiles;
    }

    function scanFilesystem($remote_file) {
        $sftp = $this->sftp;
        $dir = "ssh2.sftp://$sftp$remote_file";
        $files = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $files[] = $file;
                }
            }
        }
        closedir($handle);
        return $files;
    }
 
    function getCurrentdirfiles($dir){
        //$dir = "ftpfiles/TEST/JAYDIP/";
        $listfiles = array();
        $handle = opendir($dir);
     
        // List all the files
        while(false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != ".") {
                if (is_dir($file)) {
                //$tempArray[$file] = $this->scanFilesystem("$dir/$file");
                } else {
                    $listfiles[] = $file;
                }
            }
        }
        closedir($handle);
        return $listfiles;
    }

}

?>