Cannot upload big zip files using drop-zone in CodeIgniter - javascript

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.

Related

Wordpress Category Filtering Stuck

Everytime I click a category it shows only "Filtering..." and not loading all the post.
Filtering Issue
HTML
<div class="filters"> <span class="filter active" data-set="all"><span>Show all</span></span> <?php $categories = get_categories(array( 'hide_empty' => true, 'exclude' => array(1, 143) )); foreach ($categories as $category) : ?> <span class="filter" data-set="<?= $category->slug ?>"><span><?= $category->name ?></span></span> <?php endforeach; ?> </div>
SCRIPT
`(($) => {
const filters = $("#filterBar .filters");
const articles = $("#all-posts .articles");
filters.children('.filter').click(function(e) {
e.preventDefault();
const button = $(this),
loader = $("#loader"),
data = {
'action': 'filterposts',
'category': $(this).data('set')
};
$.ajax({
url : latest_reads_params.ajaxurl,
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
articles.html("<span class='message'>Filtering...</span>");
loader.remove();
filters.find('.active').removeClass('active');
button.addClass('active');
},
success : function( data ){
if( data ) {
data = JSON.parse(data);
articles.hide().html(data.posts).slideDown(400);
if (data.max_pages > 1) {
articles.after('<div id="loader">'+
'<span class="ibtn secondary large" id="loaderAction" data-category="'+data.category+'" data-maxpages="'+data.max_pages+'">Load more</span>'+
'</div>');
}
} else {
articles.html("<span class='message'>No post found for filter</span>");
}
}
});
});
})(jQuery);`
I wanted to display all category post

Method Illuminate\Validation\Validator::validateVideo does not exist

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.

Why could this dropzone.js not be uploading to a live server?

This implementation of dropzone.js works on my local host, but when I move it to live the files don't end up on the server:
Here's the form:
<form action="submit.php" enctype="multipart/form-data" method="POST">
<label for="fname">First name: </label>
<input type="text" name="fname" id="fname" required />
<label for="lname">Surname:</label>
<input type="text" name="lname" id="lname" required />
<div class="dropzone" id="file-upload"></div>
<button type="submit" id="submit-all">Submit</button>
</form>
I am using AJAX to submit the form:
$(document).ready(function() {
Dropzone.options.fileUpload = {
url: '/submit.php',
autoProcessQueue: false,
paramName: 'file',
uploadMultiple: true,
parallelUploads: 1,
maxFiles: 1,
maxFilesize: 10,
acceptedFiles: 'image/*,.mp4,.mkv,.avi',
addRemoveLinks: true,
init: function() {
dzClosure = this;
document.getElementById("submit-all").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("fname", jQuery("#fname").val());
formData.append("lname", jQuery("#lname").val());
});
}
}
});
});
submit.php
<?php
require_once "db.php";
$target_dir = "uploads/";
echo '<pre>';
if (move_uploaded_file($_FILES["file"]["tmp_name"][0], $target_dir.$_FILES['file']['name'][0])) {
$status = 1;
echo 'uploaded, ';
}
else {
echo 'not uploaded, ';
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
if(mysqli_query($conn, "INSERT INTO CF_form(fname, lname
) VALUES('" . $fname . "', '" . $lname . "')")) {
echo 'sent';
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
mysqli_close($conn);
As I said, this all works on my local host but on the live site the file doesn't appear. I get the 'sent' message and the debugging info is like this:
uploaded, Here is some more debugging info:
Array
(
[file] => Array
(
[name] => Array
(
[0] => IMG_1129.JPG
)
[type] => Array
(
[0] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/phpriOyPQ
)
[error] => Array
(
[0] => 0
)
[size] => Array
(
[0] => 2181000
)
)
)
sent
The uploads directory is set to 777. Just can't figure out why I'm not getting the files.

Angular JS send html to data base

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
}
});
}
}

CakePHP 3 - Deleting associated data using ajax

Posts can have multiple authors.
I want to add the possibility to delete authors in a post using Ajax.
PostsAuthorsTable.php
$this->belongsTo('Users', [
'className' => 'Users',
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
PostsTable.php
$this->hasMany('PostsAuthors', [ 'foreignKey' => 'post_id' ]);
PostsController.php
public function delete_author($authorID)
{
$id = $_GET['authorID'];
$this->Posts->PostsAuthors->delete($id);
$this->autoRender = false;
}
View: Posts > edit.ctp (JavaScript part)
<?php $this->start('script'); ?>
<script>
$(document).ready(function () {
$('.delete-author').on('click', function () {
$.ajax({
url: '<?= $this->Url->build(["action" => "delete_author"]) ?>',
type: 'GET',
data: { authorID: $(this).data('id') }
});
return false;
});
});
</script>
<?php $this->end(); ?>
View: Posts > edit.ctp (HTML part)
<?php foreach ($post_authors as $post_author): ?>
<tr>
<td><?= $post_author->user->name ?></td>
<td class="text-center">
<a href="#" class="delete-author text-danger" data-id="<?= $post_author->id ?>">
<i class="icon-trash"></i>
</a>
</td>
</tr>
<?php endforeach; ?>
Thank you for your help. :)
I found the solution.
PostsController.php
public function delete_author($authorID)
{
$id = $_GET['authorID'];
$entity = $this->Posts->PostsAuthors->get($id);
$this->Posts->PostsAuthors->delete($entity);
$this->autoRender = false;
}

Categories