leviathanz's avatar

Upload image over Javascript

I tried to make a laravel upload image with this controller:

public function addUser(Request $request){
       $user = new User();
       $user->lastName = $request->lastName;
       $user->firstName = $request->firstName;
       $user->email = $request->email;
       $user->login = $request->login;
       $user->password = bcrypt($request->password);

        if($request->image)
        {

          $original_directory = "uploads/users/";

          if(!File::exists($original_directory))
          {
            File::makeDirectory($original_directory, $mode = 0777, true, true);
          }

          $post->image = Carbon::now()->format("d-m-Y-h-i-s").$request->image->getClientOriginalName();
          $request->image->move($original_directory, $post->image);
          
        }
      $post->created_by = Auth::id();

      $post->save();

      return response()->json($post); 
 }

form in blade file (this is modal form):

<form enctype="multipart/form-data">
    <div class="form-group">
              <input type="text" id="lastName" class="form-control" placeholder="last Name" required />

            </div>
            <div class="form-group">
              <input type="text" id="firstName" class="form-control" placeholder="name" required />
            </div>
            <div class="form-group">
            <input type="email" id="email" class="form-control" placeholder="Email" required/>
            </div>
            <div class="form-group">
              <input type="text" id="login" class="form-control" placeholder="Login" required/>
            </div>
            <div class="form-group">
              <input type="password" id="password" class="form-control" placeholder="password" required/>
            </div>
            <div class="form-group">
               <input type="file" id="image" class="form-control"  required  />
            </div>
</form>

And the js script:

$(document).on('click', "#creer_utilisateur", function() {
    var lastName= $('#lastName').val();
    var firstName = $('#firstName').val();
    var email = $('#email').val();
    var login = $('#login').val();
    var password = $('#password').val();
    var image = $('#image').val();

        success: function(data) {
            $.ajax({
              url: "{{action('UserController@addUser')}}",
              method: 'POST',
              data: {
                lastName: lastName,
                firstName: firstName,
                email: email,
                login: login,
                password: password,
                image: image
              },
              success: function(data) {
			  console.log(data);
              alert('success');

              },
              error: function(){
                alert('failed');
              }
            });
        }
      });
  });

If I checked in the console log, the image form data never send. Anyone have advice how to solved this?

Thanks

0 likes
1 reply
Tray2's avatar
Tray2
Best Answer
Level 73

Try adapting this

$(document).ready(function(){

    $("#but_upload").click(function(){

        var fd = new FormData();
        var files = $('#file')[0].files;
        
        // Check file selected or not
        if(files.length > 0 ){
           fd.append('file',files[0]);

           $.ajax({
              url: 'upload.php',
              type: 'post',
              data: fd,
              contentType: false,
              processData: false,
              success: function(response){
                 if(response != 0){
                    $("#img").attr("src",response); 
                    $(".preview img").show(); // Display image element
                 }else{
                    alert('file not uploaded');
                 }
              },
           });
        }else{
           alert("Please select a file.");
        }
    });
});

Taken from this guide

https://makitweb.com/how-to-upload-image-file-using-ajax-and-jquery/

Please or to participate in this conversation.