0

i need to use javascript to update a image file from form in controller. The server response:(Internal Server Error) For more clarify i post my code: the view blade..php è:

<div class="col">
<form action="{{ route('upload.uploadImage') }}" id="imageForm" >
 @csrf
<input type="file"   onchange="loadFile(event)"> <br>        
      <img  id="output" />

</form></div>

The javascript code on view:

var loadFile = function(event) {
  var reader = new FileReader();
    reader.onload = function(){
  var output = document.getElementById('output');
    output.src = reader.result;
  var file = event.target.files[0]; 

    $.ajax({
      url: $('#imageForm').attr('action'),
      method: "POST",   
      headers: {
        'X-CSRF-TOKEN': '{{ csrf_token() }}', 
      },
      data:new FormData($('#imageForm')[0]),
      dataType:'JSON',
      contentType: false,
      cache:false,
      processData: false,
    success: (data)=> {
      console.log("Value added " + output.src);
    },
    error: function(data){
           console.log(data);}
           });

    };
    reader.readAsDataURL(event.target.files[0]);
  };

the route:

Route::post('/upload', [ImageController::class,'uploadImage'])->name('upload.uploadImage');

the ImageController:

 public function uploadImage(Request $request): JsonResponse
{

    dd('Controller method called');
    $image= new Image;
    $image->name=$request->input('name');
    
    if ($request->hasFile('image')) {
        $file=$request->file('image');
        $extension=$file->getClientOriginalExtension();
        $filename=time().'.'.$extension;
        $file->move('public/images/',$filename);
        $image->image=$filename;
       session()->put('filename', $filename);

       $image->save();
       return response()->json(['success' => 'Post created successfully.']);
    }
}

Of course, head of view has the following code:

<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
6
  • what is the server error ? Commented Mar 3, 2024 at 10:41
  • The server response: 500 (Internal Server Error). Thank you for your support. Commented Mar 3, 2024 at 15:10
  • check Laravel error log. then you should see the actual error. it will help you to rectify the issue Commented Mar 3, 2024 at 16:12
  • In the storage/logs/laravel.log i didn't receive any message. Is there another folder when i can see? I read the message 500 in the console. Commented Mar 3, 2024 at 18:26
  • use try catch . Commented Mar 4, 2024 at 6:49

0

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.