0


iam try to upload image by ajax in laravel.
here is my js code :

$('#profile_picture').on('submit', function(event){
    event.preventDefault();
    $.ajax
    ({
        type: "POST",
        url: "{{url('all/update-profile-picture')}}", 
        data:new FormData(this),
        dataType:'json',
        type:'post',
        processData: false,
        contentType: false,
        cache:false,
    }).done( function(data){
      //swal("Good job!", "Your information has been successfully updated!", "success")
          console.log('Ajax was Successful!')
          console.log(data)
    }).fail(function(xhr, textStatus, error){
        console.log(textStatus)
        console.log(error)
    });
});

here is controller code :

$validation = Validator::make($request->all(), [
    'profile_photo'=> 'required|image|mimies:jpeg,png,jpg,gif|max:2048'
]);
if ($validation->passes()) {
    //$image = $request->file('profile_photo');
    $new_name = time().'.'.$request->image->getClientOriginalExtension();
    $request->image->move(public_path("photo"),$new_name);
    return response()->json([
        'message' => 'Image uploaded successfully'
    ]);
} else {
    return response()->json([
        'message' => $validation->errors()->all(),
        'profile_photo' => '',
        'class_name' => 'danger'
    ]);
}

I hope its my controller's problem . when click submit with blank , its seen error message in console.
I don't understand whats the problem ??

1 Answer 1

1

you need to use file() method for get your request file.

$validation = Validator::make($request->all(), [
    'profile_photo'=> 'required|image|mimies:jpeg,png,jpg,gif|max:2048'
]);

if ($validation->passes()) {

    $new_name = time().'.'.$request->file('profile_photo')->getClientOriginalExtension();
    $request->file('profile_photo')->move(public_path("photo"),$new_name);

    return response()->json([
        'message' => 'Image uploaded successfully'
    ]);
} 

return response()->json([
    'message' => $validation->errors()->all(),
    'profile_photo' => '',
    'class_name' => 'danger'
]);
Sign up to request clarification or add additional context in comments.

6 Comments

i see Internal Server Error in console
iam sure my problem is if ($validation->passes()) { in this condition & i did successfully upload image without check validation.
Can you exactly see the error by inspect element then go to network tab then click on the request.
Did you import Validator class, top of your controller class ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.