How to show progress bar on ajax multiple file upload

Jquery

Posted on 26 Apr 18 by Vickey
  386

By using ajax we can send and receive response from server without refresh the webpage page. We can submit form and can upload files on server by using ajax call. But if we will upload multiple file at once then total post size will increase that will impact performance and file uploading process may be crash or kill. So the correct way is that we will send file on server one by one. In this blog we will upload multiple file one by one with progress bar. We will drag and drop multiple file and add all files in a queue and send these on server one by one with showing a progress bar. we can do this by adding a parameter 'async: false in ajax call but by doing this we can not show progress bar because synchronous ajax call will freeze ui so the progress bar will not work.so we have a another method to do this. let's start.

First of all create a html file 'index.html' and add the below code

<html>
<head>
	<script defer src="https://use.fontawesome.com/releases/v5.0.9/js/all.js"></script>
	<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
	<body style="background: #d8d2d2;">
		<form>
			<div id="dragandrophandler" style="border: 2px #478FCA dashed;width: 35%;padding: 5%;margin:0 auto;text-align: center; margin-top: 100px;">
				<i class="fas fa-cloud-upload-alt" style="font-size: 8em;color:#478FCA;"></i>
			</div>
			<div style="border:1px solid #478FCA;margin:20px auto;width: 45%;display:none;" id="file_upload_progress_bar">
  					
			</div>
		</form>
	</body>
</html>
<script>
    var obj = $("#dragandrophandler");
    obj.on('dragenter', function (e)
    {
        e.stopPropagation();
        e.preventDefault();
    });
    obj.on('dragover', function (e)
    {
        e.stopPropagation();
        e.preventDefault();
    });
    var filesForUpload = [];
    obj.on('drop', function (e)
    {
        e.preventDefault();
        var files = e.originalEvent.dataTransfer.files;
        for (var current_file = 0; current_file < files.length; current_file++)
        {
            var fd = new FormData($('#hiddenElements')[0]);
            fd.append('filesToBeUpload', files[current_file]);
            filesForUpload.push(fd);
            var total_files = parseInt(filesForUpload.length);
        }
        var uploadingStartPercentage = parseInt(100 / total_files);
        uploadingPercentage = uploadingStartPercentage;
        sendFileToServer(filesForUpload, total_files, 1, uploadingStartPercentage, uploadingPercentage);
        
    });
    function sendFileToServer(filesForUpload,total_files, currentFile, uploadingStartPercentage, uploadingPercentage)
    {
        var data = filesForUpload[0];
        filesForUpload.splice(0, 1);
        $("#file_upload_progress_bar").show();
        $.ajax({
            url: 'upload.php',
            type: "POST",
            data: data, 
            contentType: false, 
            cache: false,
            processData: false,
            success: function (responce){},
            error: function (request, status, error) { alert("File upload failed") },
            complete: function () {
                console.log(uploadingPercentage);
                $("#file_upload_progress_bar").html('<div  style="height:24px;width:'+uploadingPercentage+'%;background: #478FCA;color:#fff;padding-top: 6px;"></div>');
                if (filesForUpload.length > 0) {
                    sendFileToServer(filesForUpload,total_files,currentFile+1,uploadingStartPercentage,uploadingStartPercentage+uploadingPercentage);
                } 
                else {
                    $("#file_upload_progress_bar").html('<div  style="height:24px;width:100%;background: #478FCA;color:#fff;padding-top: 6px;"></div>');
                    //window.location = "/";
                }
            }
        });
    }
</script>

Now create a php file where we will upload file by using php

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["filesToBeUpload"]["name"]);
if (move_uploaded_file($_FILES["filesToBeUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["filesToBeUpload"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}

Thanks for reading this blog

Install or change html themes in symfony

Symfony

Posted on 28 Dec 17 by Vickey
  280

Hey guys! in this post we will implement new html themes in symfony. First of all we will install 'assetic-bundle' for manage web assets.

composer require symfony/assetic-bundle

Register this bundle in 'appAppKernel'

# app/appAppKernel.php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
        );
    }
}

Now put your css and js files in 'symfony/src/AppBundle/Resources/public/' and run command

php bin/console a:i

it will copy all css and js files and folders under 'symfony/web/bundles/app/' where app is the bundle name.Now add cssrewrite option in config file for rewrite images path  in your css files. for example it will rewrite background-image: url("../img/body-bg.jpg") to background-image: url("url("../../bundles/app/img/body-bg.jpg")")

# app/config/config.yml
assetic:
    debug:          '%kernel.debug%'
    use_controller: '%kernel.debug%'
    filters:
        cssrewrite: 

Set your template engine

# app/config/config.yml
framework:
    templating:
        engines: ['twig']

In 'app/Resources/views/base.html.twig' Load your css files

 {% block stylesheets %}

 	{% stylesheets 'bundles/app/css/style.css' filter='cssrewrite' %}
        <link rel="stylesheet" href="{{ asset_url }}" />
	{% endstylesheets %}

 {% endblock %}

Load your js files

{% block javascripts %}

        {% javascripts 'bundles/app/js/jquery.js' %}
            <script src="{{ asset_url }}"></script>
        {% endjavascripts %}

{% endblock %}

Now in your views file extent base.html.twig

# index.html.twig
{% extends 'base.html.twig' %}
{% block body %}
	page html
{% endblock %}

Now refesh your page and you will see changes

How to create service or helper in symfony

Symfony

Posted on 14 Nov 17 by Vickey
  230

By using service we can put our code in a class and  by service container we can use them our controllers

Create a new service class

#src/AppBundle/Helper/MyService.php 
 
namespace Helpers; 
use Doctrine\ORM\EntityManager; 
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; 
use Symfony\Component\HttpFoundation\RequestStack; 
class MyService 
{ 
	protected $em, $req; 
    private $path = null; 
	public function __construct(EntityManager $em, RequestStack $rs) 
    { 
        $this->em = $em; 
        $this->req = $rs; 
	} 
	public function myserviceMethod() 
    { 
        $messages = 'This is my first service'; 
        return $messages; 
    } 
}

Register Services  in services.yml file

#src/AppBundle/Resources/config/services.yml  
helpers.myService: 
        class: Helpers\MyService 
        arguments: 
            - "@doctrine.orm.entity_manager" 
            - "@request_stack" 

Use service in controller

echo $msg = $this->get('helpers.myService')->myserviceMethod(); 

 

How to use mysql database with a Node Express application

Node Js

Posted on 20 Jul 17 by Vickey
  389

Now days there are many databases in IT industry. For example NoSQL, Mongo, PostgreSQL, Oracle. But if you are working in open source (PHP) you feel comfortable with MySQL database.So if you have started in Node and Express and you are mysql lover then you can use mysql in your projects by installing MySQL npm package. With Express mostly people use mangodb but by installing NPM package we can use MySQL. So Lets start

First of all we will install npm package for MySQL Database. Open your terminal window and locate to your express project directory and run command.

npm install mysql

When the installation complete, we will create a MySQL database connection.

1. In your project root folder, create a file  name as 'database.js' and paste the below code.

var mysql = require('mysql') 
var express = require('express'); 
var app = express(); 

// CREATE DATABASE CONECTION 

var connection = mysql.createConnection({ 
  host: 'localhost', 
  user: 'root', 
  password: '', 
  database: 'express' 
}) 

connection.connect(function(err) { 
  if (err) throw err 
  console.log('You are now connected with mysql database...') 
}) 

module.exports = connection;

In this file, change your host, database name and password.

2. Open your-project/routes/index.js file import your database file.

var connection = require('../database');

3. Now go to your terminal and run command.

npm start

mak sure your mysql database is running. If you will connect with your mysql database you will see in terminal.

> node ./bin/www 

You are now connected with mysql database...

4. So lets try a mysql query.

router.get('/', function(req, res, next) {
	connection.query('SELECT * FROM users', function(err, results) {
       		 res.send(results);
    
	})

});

Paste this code in your routes/index.js. your index.js file will look like this

var express = require('express');
var router = express.Router();
var connection = require('../database');
var passwordHash = require('password-hash');

/* GET home page. */
router.get('/', function(req, res, next) {
 	connection.query('SELECT * FROM users', function(err, results) {
        res.send(results);
    })
});
module.exports = router;

Start npm again. To see the result go to yor browser and open url http://localhost:3000/

How to create and start a node express project

Node Js

Posted on 15 Jun 17 by Vickey
  206

Express is a most popular framework of node js. With Express we can create apis and web applications with different - different databases like mangodb, MySQL, PostgreSQL, Oracle . In this blog we will create a new express project step by step.

1. First of all need to install node js if installed

2. After node installation we will install EXPRESS GENERATOR. This is a platform for create a skeleton for express sites. For install Express Generator type the below command in your command prompt

npm install -g express-generator

3. Now we will create a express project. In your terminal locate to the directory where you want to create a project skeleton and type the below command. where nodetest1 is the name of your project you can chage it.

express nodetest1

when you have done you can see a new project directory at that location and this is your express project.

nodetest1/
├── bin/
 |
├── node_modules
 |
├── routes
 |
├── views
 |
├── app.js
 |
├── package.json
 |
└── public/
    

Now in terminal locate to in this directory and install npm by using command

cd nodetest1
npm install

it will install DEPENDENCIES for this projects. After complete successfull installation we will start our web server by using command

npm start

Now open your browser and open url http://localhost:3000/. Now you are running your first express projects

Crop and preview an image by using jcrop

Others

Posted on 24 May 17 by Vickey
  817

When we upload images they may not be fit to our requirement like size or height and width so we need to crop that image. Some times we upload image and then crop it in server side. But if you have a large image and you want to crop a specific part for example you have a jungle image with an elephant and you want the elephant part only then you need a special croping tool. There are many window tools to crop an image but by using jcrop we can crop our image on the same time when we upload it.Lets do it in few steps

Step 1. Create a directory with index.html file and add the below code in index.html file.

<html>
<head>
<title> Crop Image </title>
<link href="css/Jcrop.css" rel="stylesheet" type="text/css" /> 
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" /> 
<script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript' src='js/bootstrap.min.js'></script>
<script type='text/javascript' src='js/Jcrop.js'></script>
<script type='text/javascript' src='js/myjs.js'></script>
</head>
<body>
<h1>Image Crop and Preview</h1>
	<div class="form-group">
		<form >
			<input type="file" name="img" id="img">
		</form>
	</div>
	<div id="imageList"></div>
	<div id="myModal" class="modal fade" role="dialog" >
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Upload Image</h4>
                </div>
                <form  method="post" onsubmit="return checkCoords();" id="imageCropForm">
                    <div class="modal-body" style="overflow:scroll;">
                        <div class="form-group">
                            <img src="" id="cropbox" />
                            <input type="hidden" id="x" name="x" />
                            <input type="hidden" id="y" name="y" />
                            <input type="hidden" id="w" name="w" />
                            <input type="hidden" id="h" name="h" />
                            <input type="hidden" id="rowImageData" name="rowImageData" />
                        </div> 
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success" >Crop Image</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

Step 2.  Create a css and a js directory. In css directory download the jcrop.css and bootstrap.css files and in js directory download jquery.js, bootstrap.js and jcrop.js. In your index.html file add the path for these files

'<link href="css/Jcrop.css" rel="stylesheet" type="text/css" /> 
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" /> 
<script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript' src='js/bootstrap.min.js'></script>
<script type='text/javascript' src='js/Jcrop.js'></script>
<script type='text/javascript' src='js/myjs.js'></script>'

Step 3. Now we will process the file data in php a file so create a php file name as crop.php and add the below code

$rowImageData 		= 	explode(',',$_POST['rowImageData']);
$imgDataString 		= 	$rowImageData[1];
$imgMimeType 		= 	$rowImageData[0];
$imgData 			= 	base64_decode($imgDataString);
$targ_w = $_POST['w'];
$targ_h = $_POST['h'];
$jpeg_quality = 90;
$img_r = imagecreatefromstring($imgData);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
ob_start (); 
imagejpeg ($dst_r);
$image_data = ob_get_contents (); 
ob_end_clean (); 
$imgString =  $image_data_base64 = base64_encode ($image_data); 
echo $finalImage =  $imgMimeType.','.$imgString; die; 

Now you can crop any image according to your requirment. 

How to generate code for basic operations create update read and delete in symfony

Symfony

Posted on 20 Sep 16 by Vickey
  523

Like in others php frameworks we can generate basic code automatcally. For example if you have a database table and you want to write the code for  basic operation  ‘create ’, ‘Update’,’Read’ and ‘Delete’ you don not need to write code. We can create code automatically by using commands line. but for this first we need to create an entity and repository we can create this by using command lines.

Generate Entity

php bin/console doctrine:generate:entity

after generate entity we will create tables from entity

Create table into database using entity 

php bin/console doctrine:schema:update –force

this command create tables related to all entities

Now by using the below command we create code for basic operations

Generate Create, update read delete code (CRUD Operation)

php app/console generate:doctrine:crud

when process done you can see auto generated code in your project folder

 

 

How to run window based software on ubuntu

Ubuntu Desktop

Posted on 13 Aug 16 by Vickey
  481

Today window is a very popular operating system. It is easy to use and every one can use it. There are many applications that are available only window based. So if you are using ubuntu ( Linux ) and you need to use an application that is not available on ubuntu then you can install that window application on ubuntu system by using “Wine Window Program Loader”. For this you need to install “wine” in your ubuntu system

Install Wine: For install wine go to your “Ubuntu Software Center” and in search box type "wine" and you will see wine installer in the list. By clicking on install button you can install wine and now you can install or execute exe file on ubuntu system. For execute a exe file right click on the file and select “Wine Window Program Loader”.

How to install symfony framework on Ubuntu

Symfony

Posted on 02 Aug 16 by Vickey
  491

Symfony is a very powerful and popular php framework. Many other php frameworks are based on symfony. In this blog we will learn to install symfony on a ubuntu system. There are two ways to iinstall symfony.

1. Install by using composer

2. Use symfony installer

Install by using composer : For install symfony by using composer first you need to install composer ( if not already installed ). Once you have install composer open your terminal and go to directory where you want to put your projects ( in web root directory)

For example 

vickey@vickey-HP-2000-Notebook-PC:~$ cd /opt/lampp/htdocs

 

when you are in your web root directory run the below command

vickey@vickey-HP-2000-Notebook-PC:/opt/lampp/htdocs$  composer create-project symfony/framework-standard-edition myblogs "3.1.*"

here 3.1 is symfony version which will be install. One the process complete you can see new symfony projects in your web root directrory. Now run server by using the below command

php bin/console server:run

and now you can access it by url   http://127.0.0.1:8000

In other way we can istall it by using symfony installer

Use symfony installer : First need to install symfony installer. You can install it by using 

sudo curl -LsS https://symfony.com/installer -o /usr/local/bin/symfony
sudo chmod a+x /usr/local/bin/symfony

Now you can install symfony project by using the below command

symfony new my_project_name

 

 

 

How to use models in a sub folder in yii1.x

Yii

Posted on 28 May 16 by Vickey
  616

Some times we have two different types of models in our projects for example we have many models and some have prefis 'student' ( student_users ) and some have 'teacher' (teacher_users). So if you want to put these types of models in a different directory you can create a two subdirectory under your model directory and put your models here

 

models

            teacher

            student

Now you need to do some changes in your main.php file under 'protected/config'.  Open main.php file and seacrh  'import'=>'. you will see something like this

'import'=>array(

	'application.models.*',
	'application.components.*',
	'application.widgets.Notification',
	//'ext.yii-mail.YiiMailMessage'
),

change it to

'import'=>array(

	'application.models.student.*',
	'application.models.teacher.*'

	'application.components.*',
	'application.widgets.Notification',
	//'ext.yii-mail.YiiMailMessage'
),

and now can load your models from different locations

www.000webhost.com