Categories

Friday, November 22, 2024
#919814419350 therichposts@gmail.com
AjaxLaravelLaravl 5.7

How to Preview and Save multiple images in folder in Laravel with Ajax?

Laravel 7.2 routing with route group auth guard check with prefix

How to Preview and Save multiple images in folder in Laravel with Ajax?

Hello guys, welcome to therichpost.com. As I told yesterday that, I will come with next part of this Upload and save multiple images in folder in Laravel with Ajax

In my last laravel post related to upload and save  multiple images, you all guys liked that post very much so I came early with second part of that post very shortly.

Now In this post, I will tell you, How to Preview and Save multiple images in folder in Laravel with Ajax?

 

Note: This is just working test example and I am sharing because it helped me and I think, this will help others. I am writing this note because, I get so many mail regarding that my writing skills are not good and many but I want to help others in any way so please just see my thinking not my other things. Thank you all and please write comment if this code helps you because I want to know this.

 

This is interesting and useful post for every laravel developer because this post code will  be used in every laravel project.

Here is the working image of Preview Multiple Images:

How to Preview and Save multiple images in folder in Laravel with Ajax?

 

Here is the working and tested code, you need to follow:

 

1. Very first, here is the code for laravel blade template file:

Ajax played very big role in it, I did all without page refresh and on input file onchange event. On Input file Onchange event, I am uploading the files and sent them to controller with ajax. Also, After getting ajax success response back from controller file, I am showing the storing folder images into gallery div the jquery $.each function.

<style>
.gallery{margin: 10px 0;display: block;}
.imgdiv
{
    position: relative;
    width: 100px;
    height: 115px;
}
.imgdiv img{width: 100%;height: 115px;}
</style>

<form enctype="multipart/form-data" method="post">
    <div class="row">
     <div class="col-md-12 mg-t-20">
      <input id="image-upload" name="image_upload[]" type="file"  multiple/>
      <div class="gallery"></div>
      </div>
    </div>
    <div class="row">
   <div class="col-md-12 mg-t-20">
    <input class="update btn btn-purple" type="button" value="Upload Gallery" />
  </div>
  </div>
</form>


<script>

$(function() {
// Multiple images preview in browser
  
 /*Preview Image*/
 
 $("#image-upload").change(function(){
    let image_upload = new FormData();
    let TotalImages = $('#image-upload')[0].files.length;  //Total Images
    let images = $('#image-upload')[0];  

    for (let i = 0; i < TotalImages; i++) {
    image_upload.append('images' + i, images.files[i]);
    }
    image_upload.append('TotalImages', TotalImages);
        $.ajaxSetup({
                  headers: {
                    'X-CSRF-TOKEN': Laravel.csrfToken
                  }
                });
        
        $.ajax({
        url: Laravel.appUrl + '/business_owner/image-gallery/addgallery',
        type: 'POST',
        contentType:false,
        processData: false,
        data:image_upload,
            success: function(result) {
            //Preiview Image Names    
            if(result.type == "previewimage")
            {

                 // Show Images html into gallery
                 $.each(result.imagenames, function(index) {
                     $(".gallery").append("<div class='imgdiv'><img src='"+result.imagenames[index]+"'></div>");
                    
                     
                });
            }
            
            if(result.type == "error") 
            {
                //For Empty Selection or Invalid image type
                alert(result.message);
            }
            }
        }); 
 });
 /*Preview Image*/
 });
</script>

 

2. Here is the code for routes/web.php file:

In which we declare the url paths:

Route::post('BladeTeplateFileUrl', 'YourController@addgallery')->middleware('ajax');

 

3. Here is the final code for your laravel controller file YourController.php, which you have mentioned in web.php file:

I am getting ajax post data and save into the folder first and then send json response back to ajax in success function.

use Illuminate\Support\Facades\Validator; //For run laravel default valiton rule

....
 /*Upload Gallery*/
    public function addgallery(Request $request){
         // Count and check total number of images
         if($request->TotalImages > 0)
         {
            // Declare array varibale to store images data
            $imagenames = array();

            for ($x = 0; $x < $request->TotalImages; $x++) {
            if ($request->hasFile('images'.$x)) {
                
            //Image Validation Rule    
            $rules1 = ['images'.$x =>'mimes:jpeg,jpg,png'];
            $validator = Validator::make($request->all(), $rules1);

            //Not valid image extention
            if ($validator->fails()) {
                return response()->json(["message" => "Image type must be a: jpeg, jpg, png.", 'type' => 'error']);
            }

            
            $file      = $request->file('images'.$x);
            $filename  = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $picture   = date('His').'-'.$filename;
            $file->move(public_path('img/gallery-images'), $picture);
            
             // Store Images in array variable
             $imagenames[] = asset('/img/gallery-images/'.$picture);
            
             }
            
         }
         
         //Image Preview Response
         return response()->json(['type' => 'previewimage', 'imagenames' => $imagenames]);
    }
    
    //Empty Imput
    else
    {
         return response()->json(["message" => "Please select image first.", 'type' => 'error']);
    }
}
....

This is it guys, if you have any query related to this post, then please co comment below or you like this post, then also do comment below or you can ask question.

I want know your views related to this post because your view makes me encourage. This is my promise, third part of this post, will make you blush haha.

Thank you,

Ajay Malhotra

TheRichPost

 

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

6 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.