Add a file description when uploading file Yii 1 - javascript

Hello I'm using EAjaxUpload extension to upload files and its working perfectly and files are uploaded I want to add a description to each file. I used the onComplete to have the function here's my code :
$uploadfile = $this->widget('ext.EAjaxUpload.EAjaxUpload',
array(
'id' => 'uploadFile',
'config' => array(
'action' => Yii::app()->createUrl('objective/upload'),
'allowedExtensions' => array("docx", "pdf", "pptx"),//array("jpg","jpeg","gif","exe","mov" and etc...
'sizeLimit' => 5 * 1024 * 1024,// maximum file size in bytes
//'minSizeLimit'=>10*1024*1024,// minimum file size in bytes
'onComplete' => "js:function(id, fileName, responseJSON){
console.log(responseJSON);
var filedescription= prompt('file description');
if (filedescription != null) {
document.getElementById('demo').innerHTML =
filedescription;
return filedescription;
}
}",
//'messages'=>array(
// 'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
// 'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
// 'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
// 'emptyError'=>"{file} is empty, please select files again without it.",
// 'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
// ),
'showMessage' => "js:function(message){ alert(message); }"
)
));
Now I want to return var filedescription to upload action in controller. How can I do that?
Thanks,

1.onComplete is called after your upload request is already processed by "objective/upload" action. So you have possibility to ask and set description as parameter BEFORE request:
'onSubmit' => "js:function(id, fileName){
// add filedescriton to post parameters:
this.params.filedescription = 'some file description';
}"
In controller "objective/upload" action you can access it as $_POST['filedescription'].
2.Other possibility is to create separate action for saving description (and additional file processing...) and call it from onComplete:
In onComplete:
$.post( 'saveUploadedFileDescription', { filedescription: 'some file description', fileName: fileName } );
In controller:
actionSaveUploadedFileDescription($filedescription,$filename) {
// ....
}

Related

how to implement resumable large file upload in javascript and laravel

I am trying to implement large file upload with resumable.js and laravel-chunk-upload. Everything is working fine, that is I am able to upload large files properly but the problem is, if anything happens to network connection while uploading, then the uploads is not completing properly. one chunk gets error. the error is:
"message": "fopen(H:\\Codinoz\\Development\\File ECommerce\\digital-product-shopping\\storage\\app\\products/27-09-2021 CMF 20-21 before_166b6fa4934428d2952877c84bed0ef2.): Failed to open stream: Permission denied",
There is no permission problems, because the same function is working properly when there is no network problems.
current javascript code:
let browseFile = $('#browseFile');
let resumable = new Resumable({
target: '{{ route('files.upload.large') }}',
query:{_token:'{{ csrf_token() }}'} ,// CSRF token
//fileType: ['mp4'],
chunkSize: 10*1024*1024, // default is 1*1024*1024, this should be less than your maximum limit in php.ini
headers: {
'Accept' : 'application/json'
},
testChunks: false,
maxChunkRetries: 1000,
chunkRetryInterval: 2000,
throttleProgressCallbacks: 1,
});
resumable.assignBrowse(browseFile[0]);
resumable.on('fileAdded', function (file) { // trigger when file picked
showProgress();
resumable.upload() // to actually start uploading.
});
resumable.on('fileProgress', function (file) {
if(navigator.onLine === true){
// trigger when file progress update
updateProgress(Math.floor(file.progress() * 100));
}
else{
alert('no Internet');
}
});
resumable.on('fileSuccess', function (file, response) { // trigger when file upload complete
response = JSON.parse(response)
console.log('sss');
//$('#videoPreview').attr('src', response.path);
});
resumable.on('fileError', function (file, response) { // trigger when there is any error
console.log(response);
});
let progress = $('.progress');
function showProgress() {
progress.find('.progress-bar').css('width', '0%');
progress.find('.progress-bar').html('0%');
progress.find('.progress-bar').removeClass('bg-success');
progress.show();
}
function updateProgress(value) {
progress.find('.progress-bar').css('width', `${value}%`)
progress.find('.progress-bar').html(`${value}%`)
}
function hideProgress() {
progress.hide();
}
Laravel Server side code:
public function uploadLargeFiles(Request $request) {
$receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
if (!$receiver->isUploaded()) {
// file not uploaded
}
$fileReceived = $receiver->receive(); // receive file
if ($fileReceived->isFinished()) { // file uploading is complete / all chunks are uploaded
$file = $fileReceived->getFile(); // get file
$extension = $file->getClientOriginalExtension();
$fileName = str_replace('.'.$extension, '', $file->getClientOriginalName()); //file name without extenstion
$fileName .= '_' . md5(time()) . '.' . $extension; // a unique file name
$disk = Storage::disk(config('filesystems.default'));
$path = $disk->putFileAs('products', $file, $fileName);
// delete chunked file
unlink($file->getPathname());
return [
'path' => asset('storage/' . $path),
'filename' => $fileName
];
}
// otherwise return percentage information
$handler = $fileReceived->handler();
return [
'done' => $handler->getPercentageDone(),
'status' => true
];
}
I am a beginner in this, so not so good in finding solutions. Tried my best, but couldn't find any solutions. It will be so kind if you could help.
Thank you..

How can i add domain url to the url of uploaded files when selected on ckfinder

I'm setting up ckfinder on CKEditor 4. When I select an image with "browse server" button, the URL of image is: /ckfinder/userfiles/images/image.png.
But it should be full URL like: http://example.com/ckfinder/userfiles/images/image.png.
My ckeditor/config.js file:
CKEDITOR.replace( 'content_en', {
filebrowserBrowseUrl:
'./assets/app/js/ckfinder/ckfinder.html',
filebrowserImageBrowseUrl:
'./assets/app/js/ckfinder/ckfinder.html?type=Images',
filebrowserUploadUrl:
'./assets/app/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
filebrowserImageUploadUrl:
'./assets/app/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images'
});
My config.php file in ckfinder:
$config['backends'][] = array(
'name' => 'default',
'adapter' => 'local',
'baseUrl' => '/ckfinder/userfiles/',
// 'root' => '', // Can be used to explicitly set the CKFinder user files directory.
'chmodFiles' => 0777,
'chmodFolders' => 0755,
'filesystemEncoding' => 'UTF-8',
);
Please add full path in backend configuration for baseUrl property.
Instead of:
'baseUrl' => '/ckfinder/userfiles/',
Please use :
'baseUrl' => 'http://example.com//ckfinder/userfiles/',

Fine uploader, idiomatic way to add download button to each file uploaded

I've successfully implemented fine uploader into my project. I'm using the addInitialFiles method to populate it with previously uploaded files.
What I would like to do is add a download button to each file preview rendered, both as a user add's files and 'on load' when prepopulated using addInitialFiles. Adding the button to the mark up template is pretty trival, but I'm stuck on what the most idiomatic way would be to:
Listen for the click event on the download button I've added to the markup (e.g. use a fine uploader API method, or my own listener?)
How I can associate the necessary information with each button/thumbnail to envoke a file download.
I'm storing the files download url in a mongo collection that that im returning and populating the addInitial files method with.
In case it comes up: I'm not looking to have fine uploader 'handle' the download, I'm simply trying to weave the download functionality into it's UI :)
Appreciate any/all advice/pointers!
Add an anchor link to your template somewhere inside the <li>.
Listen for qq.status.UPLOAD_SUCCESS status changes.
On success, update the anchor link to point to the appropriate download endpoint. You can find the anchor link for a specific file using getItemByFileId.
You'll need to be sure your server returns the proper Content-Disposition header when responding to a download GET request.
May this help to someone to add a custom download button to each uploaded file.
I have tested for FineUploader version 5.16.2.
Used ref links - callback events & initial file list
Code for file uploader is as (used two events for the download button):
var defaultParams = {};
$('#fine-uploader-gallery').fineUploader({
template: 'qq-template-gallery',
thumbnails: {
placeholders: {
waitingPath: 'waiting-generic.png',
notAvailablePath: 'not_available-generic.png'
}
},
validation: {
itemLimit: 10,
// acceptFiles: 'image/*',
// allowedExtensions: ['mp4','jpeg', 'jpg', 'gif', 'png']
},
session: { /** initial file list **/
endpoint: '/uploaded_files',
params: defaultParams
},
request: { /** new upload file request **/
endpoint: '/upload_files'
},
callbacks: {
/** Event to initial files with download link
array(
array('id' => xxx, 'name' => xxx, 'size' => xxx, 'thumbnailUrl' => xxx, 'uuid' => xxx, 'url' => fileUrl),
array('id' => xxx, 'name' => xxx, 'size' => xxx, 'thumbnailUrl' => xxx, 'uuid' => xxx, 'url' => fileUrl2),
...
}
**/
onSessionRequestComplete: function(id, name, responseJSON){
id.forEach((item, index) => {
var serverPathToFile = item.url,
$fileItem = this.getItemByFileId(index);
if (responseJSON.status == 200) {
$($fileItem).find(".qq-download-option") /** Custom Anchor tag added to Template **/
.attr("href", serverPathToFile)
.removeClass("hide");
}
});
},
/** Event to newly uploaded file with download link
responseJSON : array('success' => 'true', 'filename' => xxx, 'unique_id' => xxx, 'url' => fileurl)
**/
onComplete: function(id, name, responseJSON, xhr){
var serverPathToFile = responseJSON.url,
$fileItem = this.getItemByFileId(id);
if (responseJSON.success) {
$($fileItem).find(".qq-download-option") /** Custom Anchor tag added to Template **/
.attr("href", serverPathToFile)
.removeClass("hide");
}
}
},
deleteFile: {
enabled: true,
forceConfirm: true,
method: 'DELETE',
endpoint: '/delete_files',
customHeaders: {},
params:defaultParams
}
});

Elfinder maxFileSize configuration

I am trying to configure elfinder maxfilesize option in connector.php array options but still I am getting this error:
File exceeds maximum allowed size.
Here is My Configuration in connector.php:
$opts = array(
// 'debug' => true,
'roots' => array(
array(
'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED)
'path' => '../files/', // path to files (REQUIRED)
'URL' => dirname($_SERVER['PHP_SELF']) . '/../files/', // URL to files (REQUIRED)
'uploadDeny' => array('all'), // All Mimetypes not allowed to upload
'uploadAllow' => array('image', 'text/plain','application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','application/x-rar-compressed, application/octet-stream','application/zip, application/octet-stream'),// Mimetype `image` and `text/plain` allowed to upload
'uploadOrder' => array('deny', 'allow'), // allowed Mimetype `image` and `text/plain` only
'accessControl' => 'access', // disable and hide dot starting files (OPTIONAL),
'uploadMaxSize' => 1000000,
)
)
);
How can I solve this issue?
Thanks

How to create a Data base row in Wordpress for uploaded objects to Amazon S3?

In my Wordpress website Users can upload video files directly to a Amazon S3 bucket (So the files don't go through my webserver.) How i should keep track of the added objects (i.e: where and how i should add a data entry in my Wordpress Database )
With the limited information provided you could post the image data using ajax. The below is simple ajax with placeholder data for the image.
var imgData = {author: 'the-author-id', img_url: 'the-url', img_type: 'the-img-type'}
$.ajax({
data : JSON.stringify(imgData),
contentType : 'application/json',
type : 'POST',
url: 'your-wordpress-post-url',
success: function () {
// do something with the success result from backend
}
});
And within WordPress you would use wp_insert_attachment()
<?php
// Prepare an array of post data for the attachment.
$attachment = array(
'post_author' => $_POST['author'],
'post_date' => current_time('mysql'),
'guid' => $_POST['img_url'],
'post_mime_type' => $_POST['img_type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', $_POST['img_url'] ),
'post_content' => '',
'post_status' => 'inherit',
'comment_status' => 'closed',
'ping_status' => 'closed',
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment );
// if fail $attach_id is 0
echo json_encode(array('attach_id' => $attach_id));
?>

Categories

Resources