Reputation: 450
Hello i'm trying to upload images to Laravel from AJAX using FormData() method. I think i'm sending good the file because if I send a file that excess the size (2mb) the server is answering me with validation error but when I send with good image properties its not saving it, I don't know why and I'm not getting any error in console, the status code is 200 OK.
I already look for another post but didnt work :/
this is part of my JS code:
$(document).ready(function(e) {
$("#uploadimage").on('submit', (function(e) {
e.preventDefault()
$('#mensaje').empty()
$('#loading').show()
var token = $('#token').val()
$.ajax({
url: '/admin/imagenes',
headers: {
"X-CSRF-TOKEN": token
},
type: 'POST',
data: ({
type: 'post',
formData: new FormData(this)
}),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$('#loading').hide()
$('#message').html(data)
}
and this is my Laravel code:
public function store(Request $request) {
if ($request->file('file')) {
$file = $request->file('file');
$name = 'NacionGrita_' .time(). '.' . $file->getClientOriginalExtension();
$path = base_path(). '/imagenes/articulos';
$file->move($path, $name);
$imagen = new Imagen();
$imagen->url = $name;
$imagen->save();
return response()->json(
$file->toArray()
);
}
}
And this my Blade code:
{!!Form::open(['route' => 'admin.imagenes.store', 'id' => 'uploadimage', 'method' => 'POST', 'files' => true])!!}
<div class="form-group ">
{!!Form::label('file', 'Imagen principal')!!}
{!!Form::file('file', null, ['class' => 'form-control', 'id' => 'file','placeholder' => 'Ingrese el título del post', 'required'])!!}
</div>
<div class="form-group ">
{!!Form::submit('Agregar Artículo', ['class' => 'btn btn-primary submit', 'id' => 'upImg'])!!}
</div>
{!!Form::close()!!}
</div>
I hope anyone can help me. Thank you so much.
Upvotes: 0
Views: 1112
Reputation: 1054
I recommend you to implement this plugin: http://malsup.com/jquery/form/#file-upload
It allows you to send files via Ajax with jquery.
Upvotes: 1