lundi 18 janvier 2021

Laravel upload image using AJAX POST method

I tried to upload an image into the form using ajax method, here the my form code in blade file:

<form action="#" id="form" enctype='multipart/form-data' class="form-horizontal">
        
        <div class="modal-header">
         <h4 class="modal-title">Data Form</h4>
       </div>
       <div class="modal-body"> 
         <div class="form-body">
 
            <div class="form-group">
              <label class="control-label col-md-4">Description</label>
              <div class="col-md-8">
                <input name="description" id="description" class="form-control" type="textarea">
                <small class="errorDescription hidden alert-danger"></small> 
              </div>
            </div> 
            
            <div class="form-group">
              <label class="control-label col-md-4">Price</label>
              <div class="col-md-8">
                <input name="price" id="price" class="form-control" type="number">
                <small class="errorPrice hidden alert-danger"></small> 
              </div>
            </div>

            <div class="form-group"> 
               <input type="file" name="image" id="image">
            </div>      
        </div>
      </div>
    </form>

And the Ajax POST method is:


    function save()
    {   
   
      var url;
      url = "";
      
      $.ajax({
        type: 'POST',
        url: url,
        data: {
          'description': $('#description').val(), 
          'price': $('#price').val(),
          'image': $('#image').val()
        },
        
        success: function(data) { 
        
        console.log(data);
            
             
          }
        }
    }

And here my controller:

  public function store(Request $request){

        // if request has file
        if($request->hasFile('image')){

            $filenameWithExt=$request->file('image')->getClientOriginalName();

            $filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);

            $extension=$request->file('image')->getClientOriginalExtension();

            $fileNameToStore= date('mdYHis') . uniqid() .$filename.'.'.$extension;

            request()->image->move(public_path('img'), $fileNameToStore);  

     }else{
           $fileNameToStore='no-image.jpeg';
      }

  $post = new WhData(); 
  $post->description = $request->description;
  $post->price = $request->price;
  $post->image=$fileNameToStore;
  $post->save();
  return redirect()->back();
  }

But the data never save the uploaded image to the DB, the Database always stored no-image.jpeg (my else condition in controller) for image value. Here my form request in the Header request data in browser console:

description: Watermelon
price: 45
image: C:\fakepath\thumbnail.jpg

Almost 3 days now to solved this and look over the net too, but still no luck. Any idea how to solved this? Thanks,



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire