Friday 21 August 2015

Laravel 5.1: Upload a image using ajax and jquery without submit a form

Hi Everybody,

In this blog we will cover upload a image in laravel 5.1 using ajax and jquery without submitting a form.

View template
ven_pers_info.blade.php

<html>
<head>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js">
<script>
$("#uploadPhoto").on("change", function (e) {
        var file_data = $("#uploadPhoto").prop("files")[0];   // Getting the properties of file from file field
        var form_data = new FormData();                  // Creating object of FormData class
        form_data.append("file", file_data)              // Adding extra parameters to form_data
        $.ajax({
            url: '/service/upload',
            dataType: 'script',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         // Setting the data attribute of ajax with file_data
            type: 'post',
            success: function (data) {
                console.log(data);
            }
        })
    })
</script>
</script>
</head>
<body>
<div class="alert alert-danger">
{{@$errors}}
</div>
<div class="alert alert-success">
{{@$success}}
</div>
<form action="/upload/photo" method="post" name="upload" enctype="multipart/form-data" id="upload">
<input id="uploadPhoto" type="file" multiple="" style="visibility: hidden; width: 1px; height: 1px" name="uploadPhoto">
<button class="btn btn-default vido_btn" onclick="document.getElementById('uploadPhoto').click(); return false" type="submit">Upload image</button>
</form>
</body>
</html>

Routes code
route.php
<?php
Route::post('upload/photo', 'VendorPersonalController@imageUpload');


Controller code
VendorPersonalController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use URL;
use App\User;

class VendorPersonalController extends Controller
{

public function __construct()
    {
        $this->uploaddir = public_path() . '/img/profile/';

    }

public function imageUpload()
    {
         $user = new User();
         if (!Input::hasFile('file')) {
            return view('ven_pers_info',['errors' => "File not found, please try again"]);
        }
        if(!$user->uploadImg('file', $this->uploaddir)){
            return view('ven_pers_info',['errors' => "File not found, please try again"]);
        }
        return view('ven_pers_info', ['success' => "File successfully uploaded"]);
}


Model code
User.php

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use DB;
use Auth;
use Illuminate\Support\Facades\Input;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['first_name','last_name', 'mobile', 'email', 'password', 'img_url', 'user_type'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

     public function uploadImg($fileField, $dirName) {
        if (Input::hasFile($fileField)) {
            $base_url = URL::to('/');
            if (!file_exists($dirName)) {
                mkdir($dirName, 0777, true);
            }
            $time = md5(microtime());
            $extension = Input::file($fileField)->getClientOriginalExtension();
            $img_hash = $base_url . '/img/profile/' . $time .'.'. $extension;
            if (!(Input::file($fileField)->move($dirName, $img_hash))) {
               return false;
            }
            return true;
        }
    }

}

If you occure some problem please comment on this post. 

Friday 7 August 2015

File uploads using Node.js

Hi Everybody,

In this blog we will cover easiest file upload mechanism using Node.js

I am going to use express framework and middleware called “multer”. This middleware is designed for handling the multipart/form-data.

In front-end script, we will set the “target” parameter of FORM to our router. for.eg  /upload/picture and in app.get(‘/upload/picture’, …) we will be able to handle our file. Let’s see how.

Our project:


This project is simple. We will have simple express web server which does the task of routing and other stuff. Multer will take care of the file handling and HTML for handling form input.

package.json
{
  "name": "file_upload",
  "version": "0.0.1",
  "dependencies": {
    "express": "~4.10.2",
    "multer": "~0.1.6"
  }
}

Installing dependency:

Save the package.json in folder and type

npm install

to install the required stuff.

Create a file Server.js in your project folder, and put below code in this

/*Define dependencies.*/

var express=require("express");
var multer  = require('multer');
var app=express();
var done=false;

/*Configure the multer.*/

app.use(multer({ dest: './uploads/',
 rename: function (fieldname, filename) {
    return filename+Date.now();
  },
onFileUploadStart: function (file) {
  console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
  console.log(file.fieldname + ' uploaded to  ' + file.path)
  done=true;
}
}));

/*Handling routes.*/

app.get('/',function(req,res){
      res.sendfile("index.html");
});

app.post('/api/photo',function(req,res){
  if(done==true){
    console.log(req.files);
    res.end("File uploaded.");
  }
});

/*Run the server.*/
app.listen(3000,function(){
    console.log("Working on port 3000");
});


Now create a view file index.html in your project folder, and put below code in this.

<form id        =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/api/photo"
     method    =  "post"
>
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
</form>

Running project:Type below command on terminal

node Server.js

to run the project. Visit localhost:3000 to view the app. Select the file and check the uploads folder. Your file must be present there!

Explanation :

In our Server.js file, we have configured multer. Multer emits event on particular situation such as we used onFileUploadStart which means when file start uploading, this event will be emitted.

After completing upload , file variable holds following array of information.
{
  userPhoto:
  {
     fieldname: 'userPhoto',
     originalname: 'banner.png',
     name: 'banner1415699779303.png',
     encoding: '7bit',
     mimetype: 'image/png',
     path: 'uploads\\banner1415699779303.png',
     extension: 'png',
     size: 11800,
     truncated: false,
     buffer: null
 }
}

We used rename function to manually pass the name of files, else by default multer use the random names for uniqueness.

As soon as onFileUploadComplete event emitted we have set the variable done to true and use it in our router to determine whether file is uploaded or not.
 if(done==true){
    res.end("File uploaded.");
  }

In HTML form you must mention enctype=”multipart/form-data” else multer will not work.
Performing file validation:

To perform validation on Server end, multer provides limits array parameter which have following parameters.
    fieldNameSize – integer – Max field name size (Default: 100 bytes)
    fieldSize – integer – Max field value size (Default: 1MB)
    fields – integer – Max number of non-file fields (Default: Infinity)
    fileSize – integer – For multipart forms, the max file size (in bytes) (Default: Infinity)
    files – integer – For multipart forms, the max number of file fields (Default: Infinity)
    parts – integer – For multipart forms, the max number of parts (fields + files) (Default: Infinity)
    headerPairs – integer – For multipart forms, the max number of header key=>value pairs to parse Default: 2000 (same as node’s http).

You can define it like this
limits: {
  fieldNameSize: 100,
  files: 2,
  fields: 5
}

In our code.
app.use(multer({ dest: './uploads/',
 rename: function (fieldname, filename) {
    return filename+Date.now();
  },
limits: {
  fieldNameSize: 100,
  files: 2,
  fields: 5
}
}));

Conclusion:


Multer is very nice middleware created by Express community. It really helps us to quickly develop critical code like File uploads in Node.js easily. I hope you find this tutorial helpful.
For any clarification comment on this post.

Thanks!!!