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. 

8 comments:

  1. Rahul thank you so much, supporting post.

    ReplyDelete
  2. I try to upload the image but there's no response when i clicked the ok button.

    ReplyDelete
    Replies
    1. First of all, i think there is no ok button.
      Can you brief me the exact problem??

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Just want to share something in here.
    https://laracast.blogspot.com/2016/06/laravel-upload-image-file-with-ajax.html

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete