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() }}" />