skip to Main Content

So im building my own website and i have this feature wherein a logged-in user can upload and change his avatar. it is my first time doing this so i am having a hard time making this work. i’ll provide the codes below, you guys might see the faults that i dont know. it will be greatly appreciated if you can provide links that will help me improve. thanks in advance!

Blade.php file

<form method='POST' action="{{ route('image-upload')  }}" enctype="multipart/form-data">
   @csrf
     <div class=" overflow-auto" style="padding-top:5%">>
      <div class="p-3">
       <div class="card">
        <div class="card-body" >
          <h4 class="card-title text-info"><strong> Attach your picture </strong></h4>
            <div class="row justify-content-center">
              <div class="col-sm-12 col-lg-4">
               <div class="form-group row">
               <label for="step5_picture" class="col-sm-3 text-right control-label col-form-label">Please upload your photo here:</label>
               <div class="col-sm-9">
               <input class="form-control" type="file" value="" id='upload_picture'  >
             </div>
            </div>
           </div>
          </div>
                
       <a href="/home"  class="btn btn-lg waves-effect waves-light btn-success" id="btn-next"  style="float:right;">Next</a>
      <button class="btn btn-lg waves-effect waves-light btn-info" id="btn-upload"  style="float:right; margin-right:10px;">Upload</button>
                </div>
            </div>
        </div>
    </div>
    </form>

Ajax code

$("#btn-upload").click(function(e){
    e.preventDefault();
    var data = {
        'photo_filename': $('#upload_picture').val(),
        }

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

  
    $.ajax({
        type: "POST",
        url: "/image-upload",
        data: data,
        dataType: "json",
        success: function (response) { 
        }
        }); 
   });

});

Controller.php file The name of the column in my database is also photo_filename

    public function image-upload(Request $request,){
    $data = UserInfoModel::where('app_id', '=' ,Session::get('loginId'))->first();
    $validator=Validator::make($request->all(), [
        'photo_filename' => 'required',
        'photo_filename.*' => 'image|mimes:jpeg,png,jpg,svg|max:5000'
        ]);
        if($request->hasfile('photo_filename')){
            $data->update([
            'photo_filename' => $request->input('photo_filename')
          ]);
            $photo = $request->file('photo_filename')->getClientOrginalName();
            $destination = public_path() . '/public/image';
            $request->file('photo_filename')->move($destination, $photo);
            return back()->with('success', 'Your image has been successfully uploaded!');
        }   
}

Web.php file

Route::post(‘/image-upload’,[CustomAuthController::class, ‘image-upload’])->name(‘image-upload’);

I am getting a payload and here it is
enter image description here

No error but still not uploading
enter image description here

2

Answers


  1. use FormData to send file in form, and add contentType: false and processData: false, you can read function setting contentType and processData in here https://api.jquery.com/jquery.ajax/

    var formData = new FormData();
    formData.append('photo_filename', $('#upload_picture')[0].files[0])
    $.ajax({
      url: "/image-upload",
      type: "post",
      data: formData,
      dataType: 'json',
      contentType: false,
      processData: false,
      success: function(response) {
          
      }
    });
    
    Login or Signup to reply.
  2. Here’s a minimal working example to create file upload in Laravel:

    blade file:

    <form method="POST" enctype="multipart/form-data" action="{{ route('save') }}">
        @csrf
        <input type="file" name="image" placeholder="Choose image" id="image">
        <button>Send</button>
    </form>
    

    Controller:

    public function save(Request $request) {
        $path = $request->file('image')->store('public/images');
        return $path;
    }
    

    web.php:

    Route::post('/foobar', [AppHttpControllersFoobarController::class, 'save'])->name('save');
    

    Please note Ajax call is not necessary here, since html form will do the POST call with the CSRF token.

    Also please note that using hyphens in function names won’t work in php.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search