i´m traying to upload a video with dropzone, i did method in controller, view, model, trait, etc... But when i call my route to my function, returned me this:
Method Illuminate\Validation\Validator::validateVideo does not exist.
i understand where i have my problem...
i attachd my actual code:
route
Route::post('uploads/storeVideo', 'UploadController#storeVideo')->name('medias.createVideo');
Controller
public function storeVideo(UploadRequest $request)
{
$input = $request->all();
try {
$upload = $this->uploadRepository->create($input);
$upload->addMedia($input['file'])
->withCustomProperties(['uuid' => $input['uuid'], 'user_id' => auth()->id()])
->toMediaCollection($input['field']);
} catch (ValidatorException $e) {
return $this->sendResponse(false, $e->getMessage());
}
}
view
<div class="form-group row">
{!! Form::label('video', trans("lang.restaurant_video"), ['class' => 'col-3 control-label text-right ']) !!}
<div class="col-9">
<div style="width: 100%" class="dropzone video" id="video" data-field="video">
<input type="hidden" name="video">
</div>
{{ trans('lang.media_select')}}
<div class="form-text text-muted w-50">
{{ trans("lang.restaurant_video_help") }}
</div>
</div>
</div>
#prepend('scripts')
<script type="text/javascript">
var var15671147011688676454bleVideo = '';
#if(isset($restaurant) && $restaurant->hasMedia('video'))
var15671147011688676454bleVideo = {
name: "{!! $restaurant->getFirstMediaVideoUrl('video')->name !!}",
size: "{!! $restaurant->getFirstMediaVideoUrl('video')->size !!}",
type: "{!! $restaurant->getFirstMediaVideoUrl('video')->mime_type !!}",
collection_name: "{!! $restaurant->getFirstMediaVideoUrl('video')->collection_name !!}"
};
#endif
var dz_var15671147011688676454bleVideo = $(".dropzone.video").dropzone({
url: "{!! url('panel/uploads/storeVideo') !!}",
/*dictDefaultMessage: "{{trans('validation.dropzone_dictDefaultMessage')}}",
dictFallbackMessage: "{{trans('validation.dropzone_dictFallbackMessage')}}",
dictFallbackText: "{{trans('validation.dropzone_dictFallbackText')}}",
dictFileTooBig: "{{trans('validation.dropzone_dictFileTooBig', [ 'size' => config('medialibrary.max_file_size') / 1024 / 1024 ])}}",
dictInvalidFileType: "{{trans('validation.dropzone_dictInvalidFileType')}}",
dictResponseError: "{{trans('validation.dropzone_dictResponseError')}}",
dictCancelUpload: "{{trans('validation.dropzone_dictCancelUpload')}}",
dictCancelUploadConfirmation: "{{trans('validation.dropzone_dictCancelUploadConfirmation')}}",
dictRemoveFile: "{{trans('validation.dropzone_dictRemoveFile')}}",*/
dictMaxFilesExceeded: "{{ trans('validation.dropzone_dictMaxFilesExceeded') }}",
maxFilesize: {!! config('medialibrary.max_file_size_video') / 1024 / 1024 !!},
acceptedFiles: "video/*",
addRemoveLinks: true,
maxFiles: 1,
init: function () {
#if(isset($restaurant) && $restaurant->hasMedia('video'))
dzInit(this, var15671147011688676454bleVideo, '{!! url($restaurant->getFirstMediaVideoUrl('video','mp4')) !!}')
#endif
this.on("error", function(file, message) {
console.log(message);
$('.video').after(`<ul class="alert alert-danger" style="list-style: none;">
<li>
${message}
</li>
</ul>`);
this.removeFile(file);
});
this.on("success", function(file, message) {
$('.alert-danger').remove();
$('.video').after(`<ul class="alert alert-success" style="list-style: none;">
<li>
{{trans('validation.dropzone_success')}}
</li>
</ul>`);
});
},
accept: function (file, done) {
dzAccept(file, done, this.element, "{!! config('medialibrary.videos_folder') !!}");
},
sending: function (file, xhr, formData) {
dzSending(this, file, formData, '{!! csrf_token() !!}');
},
maxfilesexceeded: function (file) {
dz_var15671147011688676454bleVideo[0].mockFile = '';
dzMaxfile(this, file);
},
complete: function (file) {
dzComplete(this, file, var15671147011688676454bleVideo, dz_var15671147011688676454bleVideo[0].mockFile);
dz_var15671147011688676454bleVideo[0].mockFile = file;
},
removedfile: function (file) {
dzRemoveFile(
file, var15671147011688676454bleVideo, '{!! url("panel/restaurants/remove-media") !!}',
'video', '{!! isset($restaurant) ? $restaurant->id : 0 !!}', '{!! url("panel/uploads/clear") !!}', '{!! csrf_token() !!}'
);
}
});
dz_var15671147011688676454bleVideo[0].mockFile = var15671147011688676454bleVideo;
dropzoneFields['video'] = dz_var15671147011688676454bleVideo;
</script>
#endprepend
UploadRequest deault in laravel
public function rules()
{
return [
'file' => 'image|video|mimes:jpeg,png,jpg,gif,svg,mp4,mov,avi,mkv',
];
}
Model
// VIDEO AND ALLOWED TYPES
public function getFirstMediaUrlVideo($collectionName = 'default', $conversion = '')
{
$url = $this->getFirstMediaVideoUrlTrait($collectionName);
if($url){
$array = explode('.', $url);
$extension = strtolower(end($array));
if (in_array($extension, ['.mp4', '.mkv'])) {
return asset($this->getFirstMediaVideoUrlTrait($collectionName, $conversion));
} else {
return asset('videos/' . $extension . '.mp4');
}
}else{
return asset('videos/video_default.mp4');
}
}
thanks for all help, i don´t know why does this happen. Thanks
Your error, at least the first one, is here:
public function rules()
{
return [
'file' => 'image|video|mimes:jpeg,png,jpg,gif,svg,mp4,mov,avi,mkv',
]; ^^^^^
}
There is no video validation rule (you can check the full list here). What you should do, instead, is make use of the mimes (or mimetypes) rule alone:
return [
'file' => 'mimes:mp4,mov,avi,mkv',
];
For the full list of mime extensions that you could use, here's the list.
Related
I'm trying to upload zip file using drop zone. Uploading just fine with small size zip files. However, for zip more than 5MB cannot upload. Somehow the uploading process stuck at 100% and remain there until page refresh manually.
You can see here:
after dragging the file, at 100% it getting stuck and error come up in the console.
Error:
HTML
<?php $exts = str_replace('"', '', $this->product_settings->digital_allowed_file_extensions);
$exts = str_replace(',', ", ", $exts);
$exts = strtoupper($exts); ?>
<div class="form-box">
<div class="form-box-head">
<h4 class="title">
<?php echo trans('digital_files'); ?>
<small><?php echo trans("allowed_file_extensions"); ?>: <strong class="font-500"><?php echo $exts; ?></strong></small>
</h4>
</div>
<div class="form-box-body">
<div class="row">
<div class="col-sm-12">
<div id="digital_files_upload_result" class="row-custom">
<?php $this->load->view('dashboard/product/_digital_files_upload_response'); ?>
</div>
<div class="error-message error-message-file-upload"></div>
</div>
</div>
</div>
</div>
<!-- File item template -->
<script type="text/html" id="files-template-digital-files">
<li class="media">
<div class="media-body">
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
</li>
</script>
JS: library that I'm using here: https://github.com/danielm/uploader
<script>
$('#drag-and-drop-zone-digital-files').dmUploader({
url: '<?php echo base_url(); ?>upload-digital-files-post',
queue: true,
extFilter: [<?php echo $this->product_settings->digital_allowed_file_extensions;?>],
multiple: false,
extraData: function (id) {
return {
"product_id": <?php echo $product->id; ?>,
"<?php echo $this->security->get_csrf_token_name(); ?>": $.cookie(csfr_cookie_name)
};
},
onDragEnter: function () {
this.addClass('active');
},
onDragLeave: function () {
this.removeClass('active');
},
onNewFile: function (id, file) {
ui_multi_add_file(id, file, "digital-files");
},
onBeforeUpload: function (id) {
ui_multi_update_file_progress(id, 0, '', true);
ui_multi_update_file_status(id, 'uploading', 'Uploading...');
},
onUploadProgress: function (id, percent) {
ui_multi_update_file_progress(id, percent);
},
onUploadSuccess: function (id, data) {
var obj = JSON.parse(data);
if (obj.result == 1) {
document.getElementById("digital_files_upload_result").innerHTML = obj.html_content;
}
},
onFileExtError: function (file) {
$(".error-message-file-upload").html("<?php echo trans('invalid_file_type'); ?>");
setTimeout(function () {
$(".error-message-file-upload").empty();
}, 4000);
},
});
$(document).ajaxStop(function () {
$('#drag-and-drop-zone-digital-files').dmUploader({
url: '<?php echo base_url(); ?>upload-digital-files-post',
queue: true,
extFilter: [<?php echo $this->product_settings->digital_allowed_file_extensions;?>],
multiple: false,
extraData: function (id) {
return {
"product_id": <?php echo $product->id; ?>,
"<?php echo $this->security->get_csrf_token_name(); ?>": $.cookie(csfr_cookie_name)
};
},
onDragEnter: function () {
this.addClass('active');
},
onDragLeave: function () {
this.removeClass('active');
},
onNewFile: function (id, file) {
ui_multi_add_file(id, file, "digital-files");
},
onBeforeUpload: function (id) {
ui_multi_update_file_progress(id, 0, '', true);
ui_multi_update_file_status(id, 'uploading', 'Uploading...');
},
onUploadProgress: function (id, percent) {
ui_multi_update_file_progress(id, percent);
},
onUploadSuccess: function (id, data) {
var obj = JSON.parse(data);
if (obj.result == 1) {
document.getElementById("digital_files_upload_result").innerHTML = obj.html_content;
}
},
onFileExtError: function (file) {
$(".error-message-file-upload").html("<?php echo trans('invalid_file_type'); ?>");
setTimeout(function () {
$(".error-message-file-upload").empty();
}, 4000);
},
});
});
</script>
PHP
//upload digital files
public function upload_digital_files($product_id)
{
if (isset($_FILES['file'])) {
if (empty($_FILES['file']['name'])) {
exit();
}
}
$product = $this->product_model->get_product_by_id($product_id);
if (!empty($product)) {
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$file_name = str_slug($this->general_settings->application_name) . "-digital-file-" . $product->id . uniqid() . "." . $ext;
$this->load->model('upload_model');
if ($this->upload_model->digital_file_upload('file', $file_name)) {
$data = array(
'product_id' => $product_id,
'user_id' => user()->id,
'file_name' => $file_name,
'storage' => 'local',
'created_at' => date('Y-m-d H:i:s')
);
#$this->db->close();
#$this->db->initialize();
$this->db->insert('digital_files', $data);
}
}
}
//digital file upload
public function digital_file_upload($input_name, $file_name)
{
$config['upload_path'] = './uploads/digital-files/';
$config['allowed_types'] = '*';
$config['file_name'] = $file_name;
$this->load->library('upload', $config);
if ($this->upload->do_upload($input_name)) {
$data = array('upload_data' => $this->upload->data());
if (isset($data['upload_data']['full_path'])) {
return true;
}
return null;
} else {
return null;
}
}
First of all your code's error is not clear. You can print the variable data before calling JSON.parse as follows so it shows the original error.
onUploadSuccess: function (id, data) {
console.log(data);
},
I think you are not set the content-type header to JSON in Codeigniter before returning the results.
Just add the following code in the PHP file and try
$this->response->setContentType('Content-Type: application/json');
And return responses after successful file upload
return json_encode(['status'=>'ok','path'=>'file-path']);
If it will not work then first try the demo code given in this package.
https://github.com/danielm/uploader/tree/master/demo
Answer to this issue is here.
I changed the server limits to this way and it work well now.
memory_limit = 250M //The maximum amount of memory in bytes a script is allowed to allocate.
max_input_time = 600 //The maximum time in seconds a script is allowed to parse input data.
max_execution_time = 600 //The maximum time in seconds a script is allowed to run before it is terminated.
post_max_size = 200M //The maximum size in bytes of data that can be posted with the POST method. Typically, should be larger than upload_max_filesize and smaller than memory_limit.
upload_max_filesize = 100M //The maximum size in bytes of an uploaded file.
I m sending html < p >hello< /p>
<div class="input-field">
<input id="price" type="number" ng-model="productData.price" ng-init="productData.price = ''" >
<label for="price">Price</label>
</div>
<div id="editor3" class="ql-container ql-snow">
<div class="ql-editor" data-gramm="false" contenteditable="true">
<p>hello</p>
</div>
</div>
<input type="hidden" ng-model="productData.description">
to angular js code, But it is not working. I am new to angular js. the fifth line below I thing not taking data from HTML code
$scope.addProdcut = function (productData) {
if ($scope.validateProduct(productData)) {
$scope.productLoader = true;
$('#productSubmit').attr('disabled', true);
$scope.productData.description = $('#editor3 .ql-editor').html() != '' ? $('#editor3 .ql-editor').html() : '';
var url = webroot + 'products/addProduct';
$scope.data = {
"type": "json",
"data": productData,
"image": $scope.productImage
};
$http.post(url, $scope.data, {
headers: {
'X-CSRF-Token': token
}
});
}
}
Controller file
public function addProduct()
{
if ($this->request->is('post')) {
$content = $this->request->input('json_decode', true);
$data = $content['data'];
$file = '';
if ($content['image'] != '') {
$file = date('ymd') . time() . '.' . 'jpg';
$path = WWW_ROOT . 'img/products/' . $file;
$this->base64_to_jpeg($content['image'], $path);
}
$products = TableRegistry::get('Products');
$query = $products->query()->insert(['item', 'price', 'description', 'image', 'status', 'added_by', 'created'])
->values([
'item' => $data['name'],
'price' => $data['price'],
'description' => $data['description'],
'image' => $file,
'status' => 1,
'added_by' => $this->loggedInUser['id'] . '||' . $this->loggedInUser['username'],
'created' => date("Y-m-d\TH:i:s"),
])->execute();
echo json_encode(['status' => 'success']);
exit;
}
}
it is a word editor in form, from where I want to save HTML code (from word editor) in data base using a hidden input field. by sending data ng-model to that hidden input field
You are storing the value in $scope.productData.description and then sending productData, instead, you should send $scope.productData.description.
$scope.addProdcut = function(productData) {
if ($scope.validateProduct(productData)) {
$scope.productLoader = true;
$('#productSubmit').attr('disabled', true);
$scope.productData.description = $('#editor3 .ql-editor').html() != '' ? $('#editor3 .ql-editor').html() : '';
var url = webroot + 'products/addProduct';
$scope.data = {
"type": "json",
"data": $scope.productData.description,
"image": $scope.productImage
};
$http.post(url, $scope.data, {
headers: {
'X-CSRF-Token': token
}
});
}
}
I have a view in which I need after a click to send a javascript variable to a controller which contains a form that I send to the database.
So after the click, I'm using ajax to call my controller and load the html on the same view like this:
$(".month").click(function(){
var click = $(this);
var month = click.val();
var year = $("#years").val();
var url = Routing.generate('av_platform_formulaire');
$.ajax(url,
{
type: 'GET',
data: {"month": month,
"year" : year},
dataType: "html",
success: function (data) {
$('#content').empty();
$('#content').append(data);
},
error : function(jqXHR, textStatus, errorThrown){}
});
});
So far there is no problem, my view containing the form is loading correctly and I receive the data I sent via the ajax request but when I fill my form and try to submit it, the page is refreshing and it's like nothing happens...
Here is my 2 controllers (the second is the problematic one):
public function saisieAction(Request $request){
$thisyear = date("Y");
return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
array(
'year' => $thisyear
));
}
public function formulaireAction(Request $request){
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
//$repository = $em->getRepository('AvPlatformBundle:NoteDeFrais');
// Create the form
$form = $this->get('form.factory')->createBuilder(FormType::class)
->add('ndf', CollectionType::class, array(
'entry_type' => NoteDeFraisType::class,
'label' => false,
'allow_add' => true,
'allow_delete' => true,
))
->getForm();
if ($request->isXmlHttpRequest()){
$month = $request->get('month');
$year = $request->get('year');
$sub_date = $month . '/' . $year;
}
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
// After debugging, the code inside the if is not executed
$notesDeFrais = $form['ndf']->getData();
foreach ($notesDeFrais as $ndf) {
$ndf->setUser($user);
$ndf->setMois($sub_date);
$em->persist($ndf);
}
$em->flush();
}
return $this->render('AvPlatformBundle:Platform:formulaire.html.twig',
array(
'form' => $form->createView()
));
}
My view containing the form:
<div id="ms_form">
{{ form_start(form) }}
<div id="bloc_saisie" class="fieldset">
<fieldset>
<div id="form_ndf" class="form_ndf" data-prototype="
{% filter escape %}
{{ include('AvPlatformBundle:Platform:prototype.html.twig', { 'form': form.ndf.vars.prototype }) }}
{% endfilter %}">
</div>
<div class="buttons">
<button type="button" class="fas fa-plus" id="add_ndf"></button>
<input type="submit" class="btn btn-primary btn-lg" id="next_button" >
</div>
</fieldset>
</div>
{{ form_row(form._token) }}
{{ form_end(form, {'render_rest': false}) }}
</div>
How do i return a no results label in my autocomplete when there is no matches to the data, currently it just shows nothing..
here is my current code:
HTML:
{!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
<div class="col-md-9">
{!! Form::text('searchlocation', null, array('class' => 'form-control', 'maxlength' =>'55', 'placeholder' => 'Eg. England, London or Sports', 'id' => 'sl')) !!}
</div>
{!! Form::hidden('country', null, array('id' => 'country')) !!}
{!! Form::hidden('city', null, array('id' => 'city')) !!}
<div class="col-md-3">
{!! Form::submit('Find Sights', array('class' => 'btn btn-homepage-search')) !!}
</div>
{!! Form::close() !!}
JS:
$('#sl').autocomplete({
source: '/autocomplete',
select: function(event, ui) {
event.preventDefault();
$("#country").val(ui.item.country);
$("#city").val(ui.item.value);
$('#sl').val(ui.item.label);
},
focus: function(event, ui){
event.preventDefault();
$('#sl').val(ui.item.label);
},
})
You can set this in php as :
if(count($usersArray) < 1){
$usersArray[] = array(
"label" => "No Result",
"value" => "-1",
"country" => "-1"
);
}
you can use client side check to show no records found. please take a look below.
$(function() {
$("#SearchUser").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://api.stackexchange.com/2.1/users",
data: {
site: 'stackoverflow',
inname: request.term
},
dataType: 'jsonp'
}).done(function(data) {
if (data.items) {
response($.map(data.items, function(item) {
console.log(item);
return item.display_name + " " + item.location;
}));
}
});
},
minLength: 1,
response: function(event, ui) {
if (!ui.content.length) {
var message = { value:"",label:"No records found" };
ui.content.push(message);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" rel="stylesheet"/>
<label for="SearchUser">StackOverflow user:</label>
<input id="SearchUser" type="text" />
.
I have a form with three post data along with that I have to append a filedata(input type="file"). I didn't get the filedata, when I alert the post data in js. How can I resolve it? please suggest a solution..
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/Q0qdk.png
$('#employerid_contactus').click(function (event) {
cs_data_loader_load('#cs_employer_contactus #loader-data');
var default_message = jQuery("#cs_employer_contactus").data('validationmsg');
event.preventDefault();
var ajaxurl = jQuery(".cs-profile-contact-detail").data('adminurl');
var employerid = jQuery(".profile-contact-btn").data('employerid');
var captcha_id = jQuery(".cs-profile-contact-detail").data('cap');
jQuery.ajax({
type: "POST",
url: ajaxurl,
dataType: "html",
data: $('#ajaxcontactemployer').serialize() + "&employerid=" + employerid + "&action=ajaxcontact_employer_send_mail",
success: function (response) {
jQuery("#ajaxcontactemail").removeClass('has_error');
jQuery("#ajaxcontactname").removeClass('has_error');
jQuery("#ajaxcontactcontents").removeClass("has_error");
var pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
var response_data = response.split("|");
if (jQuery("#ajaxcontactname").val() == '') {
jQuery("#ajaxcontactname").addClass('has_error');
} else
if (!pattern.test(jQuery("#ajaxcontactemail").val())) {
jQuery("#ajaxcontactemail").addClass('has_error');
} else
if (jQuery("#ajaxcontactcontents").val().length < 35) {
jQuery("#ajaxcontactcontents").addClass('has_error');
}
var error_container = '';
if (response_data[1] == 1) {
error_container = '<div class="alert alert-danger"><button aria-hidden="true" data-dismiss="alert" type="button" class="close">×</button><p><i class="icon-warning4"></i>' + response_data[0] + '</p></div>';
jQuery("#ajaxcontact-response").html(error_container);
} else {
error_container = '<div class="alert success"><button aria-hidden="true" data-dismiss="alert" type="button" class="close">×</button><p><i class="icon-warning4"></i>' + response_data[0] + '</p></div>';
jQuery("#ajaxcontact-response").html(error_container);
jQuery("#ajaxcontactcontents").val('');
captcha_reload(ajaxurl, captcha_id);
}
jQuery('#cs_employer_contactus #loader-data').html('');
}
});
return false;
});
this is how form view code:
<div class="input-filed"> <i class="icon-mobile4"></i>
<?php
$cs_opt_array = array(
'id' => '',
'std' => isset($login_user_phone) ? esc_html($login_user_phone) : '',
'cust_id' => "ajaxcontactphone",
'cust_name' => "ajaxcontactphone",
'classes' => 'form-control',
'extra_atr' => 'placeholder="' . esc_html__('Phone Number', 'jobhunt') . '"',
);
$cs_form_fields2->cs_form_text_render($cs_opt_array);
?>
</div>
<div class="input-filed"> <i class="icon-mobile4"></i>
<?php
$cs_opt_array = array(
'id' => '',
'std' => '',
'cust_id' => "ajaxcontactfile",
'cust_name' => "ajaxcontactfile",
'cust_type' => "file",
'classes' => 'form-control',
'extra_atr' => '',
);
$cs_form_fields2->cs_form_text_render($cs_opt_array);
?>
</div>
When serialize the postdata I didn't get the filedata
I need to send an email using ajax. I can send name, email and phone number but not the file. I need to include file along with these fields. When I alert the serialized data in js it not showing the filedata. How can I append the file with postdata. Please help me with this.