Reputation: 1081
I have a Laravel 5.2 application, where i try to upload some files trough ajax, but the laravel does not receives them.
Here is my code:
function uploadImages(selector){
var file_data = selector.prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
jQuery.ajax({
url: '/uploadfile/',
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(php_script_response){
console.log(php_script_response);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus);
console.log(errorThrown);
}
});
}
Here is the php part:
public function uploadPhoto(Request $request){
$string = str_random(40);
$response = [];
$file = $request->file('file');
$response['str'] = $file;
return response()->json($response);
}
The problem is, that $file is NULL
. (the success function prints Object { str: "NULL" }
to console).
I checked the headers sent in the Network tab of the console, and it seems the image is sent as expedted. Does anybody have any idea?
UPDATE:
Here is the html form:
<form action="" method="post" enctype="multipart/form-data">
<input type='file' id='choosePhoto' name='file'>
</form>
Upvotes: 1
Views: 941
Reputation: 1054
I recommend to use this jquery plugin: http://malsup.com/jquery/form/#file-upload
Add this on your js:
$('#my-form').ajaxForm({
beforeSubmit: function(formData, jqForm, options){
// just like jquery ajax
},
success: function(responseText, statusText, xhr, $form){
console.log(responseText);
},
clearForm: true //clear form after submit
});
Then on your view:
<form id="my-form" method="POST" action="{{ URL::to('my/route') }}" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*" required>
<input class="subir" type="submit" name="submit" value="Upload">
{{ csrf_field() }}
</form>
Upvotes: 2
Reputation: 950
From the above code what i understood is problem you are having is not with the laravel uploader but with the jquery snippet. In jquery you have to handle file uploads in a different way. please find the tutorial on creating a snippet to upload files via ajax/jquery here
Upvotes: 1