Showing posts with label image upload. Show all posts
Showing posts with label image upload. Show all posts

Thursday, 30 April 2020

Vue js File Upload with PHP & Axios



This post will guide you to How to upload files using Vue.js with PHP script and Axios package. This post will help your to uploading files with VueJS with Axios. As a programmer we have already know file upload is one or the basic feature which has been required in any web based application for store or upload file on server. In this post, we will use Vue.js library & Axios package as front end technology and PHP will be use as back end technology for upload files on server.

For upload file, here we have use Axios package with Vue.js library, by using this Axios package we will send Ajax request for upload file. For send selected file here we have use FormData object, which will send file via Ajax request to PHP script. Do you know Vue.js and Axios package is work together for send HTTP requests. But here we want to send file via Ajax request for Uploading and it is little bit challenging task, because here we have to use Axios package for send file to PHP script. For this here we have use FormData() object for send selected file to PHP script via Ajax request. This tutorial will provide you simple and quick guide for handle file upload process in VueJS with PHP script.







First we have to import Vue.js and Axios package in our working index page. For this you can see below code in which we have import VueJS library and Axios package link at the header of file.


<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


First in Vue application, we have to define element for Vue appliction. For this we have to define in any tag with id="uploadApp" This attribute value will be used in the property of el: which binds the new Vue object to HTML tag with id="uploadApp".


<div class="container" id="uploadApp">

</div>


After for display upload file validation error and success message, here we have use Bootstrap alert class. Within Bootstrap alert class we have use v-if directive for display alert message on condition. If this v-if directive value is equal to true then it will display validation error or success message on web page, otherwise it will be hide from web page. Same way for display dynamic error or success message, here we have use double braces {{ }} as place-holders for data. This data value will be define on different event.


<div class="container" id="uploadApp">
   <br />
   <h3 align="center">How to upload file using Vue.js with PHP</h3>
   <br />
   <div v-if="successAlert" class="alert alert-success alert-dismissible">
    <a href="#" class="close" aria-label="close" @click="successAlert=false">&times;</a>
    {{ successMessage }}
   </div>

   <div v-if="errorAlert" class="alert alert-danger alert-dismissible">
    <a href="#" class="close" aria-label="close" @click="errorAlert=false">&times;</a>
    {{ errorMessage }}
   </div>
</div>


After this we have to create input file tag for select image or file from local computer. In input file tag we have use ref='file' which will be used for get the selected file in Vue Script.

Once file has been selected then for upload file on server, here we have define one button tag. In that button we have define @click directive. So when we have click on button, then it will called uploadImage() function.

After uploading of image, now we want to display on web page. So here we have create on div tag and under that tag we have use v-html directive. This directive is used to display HTML code under that tag.


<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>How to upload file using Vue.js with PHP</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  
 </head>
 <body>
  <div class="container" id="uploadApp">
   <br />
   <h3 align="center">How to upload file using Vue.js with PHP</h3>
   <br />
   <div v-if="successAlert" class="alert alert-success alert-dismissible">
    <a href="#" class="close" aria-label="close" @click="successAlert=false">&times;</a>
    {{ successMessage }}
   </div>

   <div v-if="errorAlert" class="alert alert-danger alert-dismissible">
    <a href="#" class="close" aria-label="close" @click="errorAlert=false">&times;</a>
    {{ errorMessage }}
   </div>
   <div class="panel panel-default">
    <div class="panel-heading">
     <div class="row">
      <div class="col-md-6">
       <h3 class="panel-title">Upload File</h3>
      </div>
      <div class="col-md-6" align="right">
       
      </div>
     </div>
    </div>
    <div class="panel-body">
     <div class="row">
      <div class="col-md-4" align="right">
       <label>Select Image</label>
      </div>
      <div class="col-md-4">
       <input type="file" ref="file" />
      </div>
      <div class="col-md-4">
       <button type="button" @click="uploadImage" class="btn btn-primary">Upload Image</button>
      </div>
     </div>
     <br />
     <br />
     <div v-html="uploadedImage" align="center"></div>
    </div>
   </div>
  </div>
 </body>
</html>





So, here our HTML code part is ready, now we have go to Vue.js code part. In this part, Vue JS has been initialize on #uploadApp.

After this, we have to define data for Vue.js application, here we have to define file variable with blank value, successAlert with false value for hide success message from web page, and same way for hide error alert message here also we have define errorAlert variable with false value. For clear uploaded image division tag data, here also we have set uploadImage variable with blank value.

After define data, we have to define methods, so in this section we have create uploadImage() function which will be called after click on upload button. In this function, first we have add selected file in Vue JS for send selected file to PHP script. Here we have use FormData object for send selected file to PHP script. We will append selected file in FormData() object as data.

After appending data in formData as data, we want to send POST request to upload.php file and pass formData in which we have append selected file has been send with post request as data. We have also set Content-Type: 'multipart/form-data' in header. Once image has been successfully uploaded then it will display success message on web page with uploaded image and suppose there is any error occur during uploading of file then it will display validation error on web page.


<script>

var application = new Vue({
 el:'#uploadApp',
 data:{
  file:'',
  successAlert:false,
  errorAlert:false,
  uploadedImage:'',
 },
 methods:{
  uploadImage:function(){

   application.file = application.$refs.file.files[0];

   var formData = new FormData();

   formData.append('file', application.file);

   axios.post('upload.php', formData, {
    header:{
     'Content-Type' : 'multipart/form-data'
    }
   }).then(function(response){
    if(response.data.image == '')
    {
     application.errorAlert = true;
     application.successAlert = false;
     application.errorMessage = response.data.message;
     application.successMessage = '';
     application.uploadedImage = '';
    }
    else
    {
     application.errorAlert = false;
     application.successAlert = true;
     application.errorMessage = '';
     application.successMessage = response.data.message;
     var image_html = "<img src='"+response.data.image+"' class='img-thumbnail' width='200' />";
     application.uploadedImage = image_html;
     application.$refs.file.value = '';
    }
   });
  }
 },
});
</script>


upload.php


So here our HTML and Vue JS code is ready now we have move to write PHP code in upload.php file. This file will first check user has select file or not, if user has not select file then it will display validation error.

If User has select file, then it will proceed for another validation and it will check selected file has valid extension. If selected file has not valid extension then it will display validation error on web page.

If Selected file has valid extension, then it will first create new name for selected file before uploading of image. After this it will upload selected image file in upload directive and send success message with uploaded image path as data to Axios request in json format. Below you can find complete PHP script for upload image in upload directive.


<?php

//upload.php

$image = '';

if(isset($_FILES['file']['name']))
{
 $image_name = $_FILES['file']['name'];
 $valid_extensions = array("jpg","jpeg","png");
 $extension = pathinfo($image_name, PATHINFO_EXTENSION);
 if(in_array($extension, $valid_extensions))
 {
  $upload_path = 'upload/' . time() . '.' . $extension;
  if(move_uploaded_file($_FILES['file']['tmp_name'], $upload_path))
  {
   $message = 'Image Uploaded';
   $image = $upload_path;
  }
  else
  {
   $message = 'There is an error while uploading image';
  }
 }
 else
 {
  $message = 'Only .jpg, .jpeg and .png Image allowed to upload';
 }
}
else
{
 $message = 'Select Image';
}

$output = array(
 'message'  => $message,
 'image'   => $image
);

echo json_encode($output);


?>


So, this is complete step by step guide for upload file using Vue.js with PHP script and Axios package. I hope you have understand this file uploading process using VueJS with PHP script.

Sunday, 19 April 2020

Drag and Drop Multiple File upload in Laravel 7 using Dropzone.js



In this tutorial, We have define How can we use Dropzone.js library for drag and drop multiple image file upload in Laravel 7 framework. If you are looking for learn How to upload multiple image using Dropzone.js library with Laravel 7 framework. Then you have come on the right place, where we have make this tutorial in which we have describe step by step tutorial on implementing Dropzone.js library with Laravel 7 framework for upload drag and drop image under Laravel public directory. In this tutorial, we have not only learn you how to upload image in Laravel 7 framework by using Dropzone.js library but also we have describe how to display images from Laravel public directory with remove image link.

Dropzone.js library is the jQuery plugin and by using this plugin we can select image one by one with image preview. By using this plugin, when we have select image from our local computer then first Dropzone.js plugin has display image preview on web page before uploading of image. By using Dropzone plugin, we can validate maximum uploading of image or file, we can define image or extension for validation. Dropzone is very famous, open source library, which we can use at free of cost. This library has provide feature like drag and drop upload multiple files or multiple image with preview of image.

Here we have use Dropzone.js library with Laravel 7 framework and make simple Laravel application for upload multiple file with drag and drop image upload feature. For upload image with preview image in Laravel framework, we have use Dropzone.js library. By using this library we have develop laravel application with drag and drop image upload feature. Once image has been uploading in Laravel public folder, then after we have fetch image from Laravel public folder and display on web page. At the last of tutorial, you can also find how to delete or remove image from Laravel public folder in Laravel framework. In this tutorial, we have use Ajax with Laravel 7 framework for fetch and display image from Laravel public directory and for delete or remove image in Laravel framework. Below you can find step by step process for how to use Dropzone.js library in Laravel 7 framework.

  1. Install Laravel 7 framework
  2. Create Controller in Laravel 7
  3. Create View File in Laravel 7
  4. Set Route
  5. Run Laravel 7 Application
.




Step1 - Install Laravel 7 framework


If you have decided to use Laravel framework for web development. Then first we have make download and install Laravel 7 framework. For this we have to go command prompt and first run composer, this is because Laravel framework dependency has been manage by composer. After this we have go directory in which we want to download and install Laravel 7 framework and write following command.


composer create-project --prefer-dist laravel/laravel laravel7


This command will download and install Laravel 7 framework in define directory.




Step2 - Create Controller in Laravel 7


After download and installing of Laravel 7 framework, In this post first we want to make controller for handle http request. In Laravel 7 framework controller class has been store in app/Http/Controllers folder. All controller file will be store under this folder. For create new controller class, we have to go command prompt and write following command.


php artisan make:controller DropzoneController


This command will make DropzoneController.php class in app/Http/Controllers folder. For upload drag and drop image upload in Laravel 7 framework using Dropzone.js plugin, we have make following method in this controller class.

index() - This is root method of this controller class, and it will load dropzone.blade.php view file in browser.
upload(Request $request) - This method will received upload image request from Dropzone.js plugin. This method will upload image in Laravel public directory.
fetch() - This method will received ajax request for fetch images from Laravel public folder and send image data to ajax request which will be display on web page.
delete(Request $request) - This method also received ajax request for delete or remove image from Laravel public folder. This method will received image name and based on image name it will delete or remove image from Laravel public directory.

app/Http/Controllers/DropzoneController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DropzoneController extends Controller
{
    function index()
    {
     return view('dropzone');
    }

    function upload(Request $request)
    {
     $image = $request->file('file');

     $imageName = time() . '.' . $image->extension();

     $image->move(public_path('images'), $imageName);

     return response()->json(['success' => $imageName]);
    }

    function fetch()
    {
     $images = \File::allFiles(public_path('images'));
     $output = '<div class="row">';
     foreach($images as $image)
     {
      $output .= '
      <div class="col-md-2" style="margin-bottom:16px;" align="center">
                <img src="'.asset('images/' . $image->getFilename()).'" class="img-thumbnail" width="175" height="175" style="height:175px;" />
                <button type="button" class="btn btn-link remove_image" id="'.$image->getFilename().'">Remove</button>
            </div>
      ';
     }
     $output .= '</div>';
     echo $output;
    }

    function delete(Request $request)
    {
     if($request->get('name'))
     {
      \File::delete(public_path('images/' . $request->get('name')));
     }
    }
}
?>


Step3 - Create View File in Laravel 7


In Laravel framework, View file has been used for display HTML output in browser. In this file we have include jQuery, Bootstrap and Dropzone.js library url. In this file we have use Dropzone.js plugin for drag and drop upload image file in Laravel framework. Once image has been uploaded, then in this file we have write Ajax request for fetch images from Laravel public directory and display on web page. And Same way for delete image from Laravel public folder, here also we have write Ajax request for delete image from Laravel public directory. Below you can find source code of dropzone.blade.php file.

resources/views/dropzone.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Image Upload in Laravel using Dropzone</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"></script>
 </head>
 <body>
  <div class="container-fluid">
      <br />
    <h3 align="center">Image Upload in Laravel using Dropzone</h3>
    <br />
        
      <div class="panel panel-default">
        <div class="panel-heading">
          <h3 class="panel-title">Select Image</h3>
        </div>
        <div class="panel-body">
          <form id="dropzoneForm" class="dropzone" action="{{ route('dropzone.upload') }}">
            @csrf
          </form>
          <div align="center">
            <button type="button" class="btn btn-info" id="submit-all">Upload</button>
          </div>
        </div>
      </div>
      <br />
      <div class="panel panel-default">
        <div class="panel-heading">
          <h3 class="panel-title">Uploaded Image</h3>
        </div>
        <div class="panel-body" id="uploaded_image">
          
        </div>
      </div>
    </div>
 </body>
</html>

<script type="text/javascript">

  Dropzone.options.dropzoneForm = {
    autoProcessQueue : false,
    acceptedFiles : ".png,.jpg,.gif,.bmp,.jpeg",

    init:function(){
      var submitButton = document.querySelector("#submit-all");
      myDropzone = this;

      submitButton.addEventListener('click', function(){
        myDropzone.processQueue();
      });

      this.on("complete", function(){
        if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
        {
          var _this = this;
          _this.removeAllFiles();
        }
        load_images();
      });

    }

  };

  load_images();

  function load_images()
  {
    $.ajax({
      url:"{{ route('dropzone.fetch') }}",
      success:function(data)
      {
        $('#uploaded_image').html(data);
      }
    })
  }

  $(document).on('click', '.remove_image', function(){
    var name = $(this).attr('id');
    $.ajax({
      url:"{{ route('dropzone.delete') }}",
      data:{name : name},
      success:function(data){
        load_images();
      }
    })
  });

</script>



Step4 - Set Route


In next step we have to set route of all DropzoneController.php controller method. For this we have to open routes/web.php file and in this file we have to set route of all controller method.

routes/web.php

Route::get('/', function () {
    return view('welcome');
});

Route::get('dropzone', 'DropzoneController@index');

Route::post('dropzone/upload', 'DropzoneController@upload')->name('dropzone.upload');

Route::get('dropzone/fetch', 'DropzoneController@fetch')->name('dropzone.fetch');

Route::get('dropzone/delete', 'DropzoneController@delete')->name('dropzone.delete');


Step5 - Run Laravel 7 Application


Once your all code is ready and have you set route of all controller method, then at last we have to run Laravel 7 server. For this we have to go command prompt and write following command.


php artisan serve


This command will start Laravel 7 server and return you base url of your Laravel 7 application. If you want to run above code, you have to write following url in browser.


http://127.0.0.1:8000/dropzone


So, this is complete step by step process of integrating Dropzone.js plugin in Laravel 7 framework for drag and drop upload multiple images in Laravel 7 public directory and then after fetch image from Laravel 7 framework public folder and display on web page and lastly how to delete or remove image from Laravel framework public directory using Ajax.

Wednesday, 14 November 2018

How to Store Multiple Images in Database using PHP Ajax



In Web development file or image upload is a very required feature. There are many ways we can store images. One we can upload image on server and store image name in Mysql database using PHP. In another way we can directly store images in Mysql database table using PHP also. There are many post we have publish on upload single image or multiple images on server and store image details in database using PHP. But in this post we have convered one advance topic like how to insert multiple image in mysql database using PHP with Ajax.

In one of our previous post we have step by step describe how to insert and fetch images from Mysql database using PHP. But in that post we have use only PHP script for insert image into mysql database and then after fetch images from Mysql database and display on web page using PHP. But here we have make one form with option like select multiple images at the same time and by using jQuery Ajax send that images data to PHP. In PHP script it will convert image into binary string format and insert into Mysql database one by one. After inserting multiple images into Mysql database, now we want to retrieve images from mysql database and display on web page. For this also we have use jQuery and Ajax function which send request to PHP, at PHP script that fetch data from mysql table and convert that data into html format and send back to ajax request. Now we have discuss source of How to Upload Multiple Images in Database using PHP Ajax.








Mysql Database


Run following SQL script into your phpMyadmin, this script will make tbl_images table into your database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_images`
--

CREATE TABLE `tbl_images` (
  `image_id` int(11) NOT NULL,
  `images` longblob NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_images`
--
ALTER TABLE `tbl_images`
  ADD PRIMARY KEY (`image_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_images`
--
ALTER TABLE `tbl_images`
  MODIFY `image_id` int(11) NOT NULL AUTO_INCREMENT;


database_connection.php


This PHP script will make Mysql database connection.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

?>


index.php


This index file of this source code in this file you can find following things.

  • HTML form for select multiple images from local computer space with image selection validation.
  • jQuery script for submit form data to PHP script using Ajax.
  • Selected image has been send to PHP script using new FormData() object.
  • Ajax script send request for images and display on web page.



<!DOCTYPE html>  
<html>  
    <head>  
        <title>Webslesson Tutorial | Insert Multiple Images into Mysql Database using PHP</title>  
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
    </head>  
    <body>  
        <br /><br />  
        <div class="container">  
   <h3 align="center">Insert Multiple Images into Mysql Database using PHP</h3>  
            <br />  
            <form method="post" id="upload_multiple_images" enctype="multipart/form-data">
                <input type="file" name="image[]" id="image" multiple accept=".jpg, .png, .gif" />
                <br />
                <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
            </form>
            <br />  
            <br />
   
            <div id="images_list"></div>
            
        </div>  
    </body>  
</html>  
<script>  
$(document).ready(function(){

    load_images();

    function load_images()
    {
        $.ajax({
            url:"fetch_images.php",
            success:function(data)
            {
                $('#images_list').html(data);
            }
        });
    }
 
    $('#upload_multiple_images').on('submit', function(event){
        event.preventDefault();
        var image_name = $('#image').val();
        if(image_name == '')
        {
            alert("Please Select Image");
            return false;
        }
        else
        {
            $.ajax({
                url:"insert.php",
                method:"POST",
                data: new FormData(this),
                contentType:false,
                cache:false,
                processData:false,
                success:function(data)
                {
                    $('#image').val('');
                    load_images();
                }
            });
        }
    });
 
});  
</script>





insert.php


This insert.php file, in this file you can find PHP script for Insert Multiple images into Mysql database. This file has received ajax request for insert multiple file into Mysql database. First, this script check there is any image file has been received or not, if received then it will check how many image insert has been received. After this this PHP script insert images into Mysql database. Before insert imag into mysql database, first it has convert into binary string format using file_get_contents() function and then at it has make insert query and run insert query and store multiple images into mysql database.


<?php

//insert.php

include('database_connection.php');

if(count($_FILES["image"]["tmp_name"]) > 0)
{
 for($count = 0; $count < count($_FILES["image"]["tmp_name"]); $count++)
 {
  $image_file = addslashes(file_get_contents($_FILES["image"]["tmp_name"][$count]));
  $query = "INSERT INTO tbl_images(images) VALUES ('$image_file')";
  $statement = $connect->prepare($query);
  $statement->execute();
 }
}


?>


fetch_images.php


This PHP script received Ajax request for retrieve images from Mysql database. This PHP script retrieve images from Mysql database and after this convert into HTML format and send to Ajax request. For convert binary string to images, here we have use base64_encode() function.


<?php

//fetch_images.php

include('database_connection.php');

$query = "SELECT * FROM tbl_images ORDER BY image_id DESC";

$statement = $connect->prepare($query);

$output = '<div class="row">';

if($statement->execute())
{
 $result = $statement->fetchAll();

 foreach($result as $row)
 {
  $output .= '
  <div class="col-md-2" style="margin-bottom:16px;">
   <img src="data:image/jpeg;base64,'.base64_encode($row['images'] ).'" class="img-thumbnail" />
  </div>
  ';
 }
}

$output .= '</div>';

echo $output;

?>