I am trying to upload photo in Laravel using jQuery AJAX. But it's always failed many times with error message
The photo must be an image. The photo must be a file of type: jpeg, png, jpg, gif, svg.
I have no idea why. What's wrong with my code below?
Controller
$validator = \Validator::make($request->all(), [
'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($files = $request->file('image')) {
//insert new file
$destinationPath = 'public/product_images/'; // upload path
$image_path = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $image_path);
}
$productId = DB::table('products')->insertGetId(
[
'product_photo' => $image_path
]
);
View
$("#photo").fileinput({
theme: 'fa',
uploadUrl: '',
uploadExtraData: function() {
return {
_token: $("input[name='_token']").val(),
};
},
allowedFileExtensions: ['jpg', 'png', 'gif'],
overwriteInitial: false,
maxFileSize: 2000,
maxFilesNum: 5,
slugCallback: function(filename) {
return filename.replace('(', '_').replace(']', '_');
}
});
$('#saveBtnForCreate').click(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "",
method: 'post',
enctype: 'multipart/form-data',
cache: false,
dataType: 'JSON',
data: {
photo: $('#photo').val()
},
success: function(result) {
if (result.errors) {
$('.alert-danger').html(
'An error in your input!'
);
$.each(result.errors, function(key, value) {
$('.alert-danger').show();
$('.alert-danger').append('<strong><li>' + value +
'</li></strong>');
});
}
}
});
});
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire