CKEditor Plug-In: Getting text of drop-down item - javascript

I created a plug-in for CKEditor that opens a dialog with a drop-down. In that drop-down is a list of files the user has uploaded outside of CKEditor. The plan is to insert a "tag" into the text containing that filename, something like [[myfile.pdf]] and then when I display the actual page, I will insert a link to that file.
The problem is that the drop-down box being created by CKEditor is listing the filename (properly) but when I select it, it inserts the file's SIZE into the text rather than the filename. When the plug-in runs, it does an ajax call and grabs a directory listing of the user's files, which is where that number comes from; I think it's confusing it with a file ID.
Here's the meat of the plug-in. I left out the ajax call for brevity. It populates the variable "items."
EDIT: I modified the results returned from the ajax call to just return the filename, and then to return the filename (twice) using two different column names (name and filename) and in both cases, the inserted value was NULL. It just doesn't want to insert a text value it seems.
I also tried changing the values of id: under contents and also under elements (alternately) between tab-basic and linkType, and I got an error in the JS console about cannot read property getValue of undefined. Curses, foiled again!
ANOTHER EDIT: I tried putting the names of the files in a database table and I return that to the plug-in instead of the directory listing. If I select filename, attachmentid (in that order), the OPTION box lists the attachmentid, and inserts the filename. If I select attatchmentid, filename it will do it the exact opposite. So then I thought, gee, what if I selected the filename twice? So I did select filename, filename as filename2. And it works! This still isn't an ideal solution so I'm hoping somebody will know the proper way to do it.
CKEDITOR.dialog.add('attachfileDialog',function(editor){
return {
title:'Attach File',
minWidth:400,
minHeight:200,
contents:[{
id:'tab-basic',
label:'Choose File',
elements:[{
type:'select',
id:'linkType',
label:'Choose File',
items:items,
'default':''
}]
}],
onOk:function(data){
var dialog = this;
var componentType = dialog.getValueOf('tab-basic','linkType');
var selectedText = editor.getSelection().getSelectedText();
if(componentType != ''){
editor.insertText('[[' + componentType + ']]');
}
}
};
});
I actually copied this from another plug-in and modified it to suit, so I'll admit I don't much know what I'm doing here. I've dug through the CKEditor docs but they aren't particularly helpful.
The variable componentType is coming back with the file size. I'm just not sure how to make it grab the text instead of the value; if you view the source, the has the value of the file size, and the text is the filename.
Any ideas? Thank you!

Related

Difficulty understanding code which retrieves a filename from a file control

I have this code in a project. I understand that it outputs the file from a file input control. The issue is that I don't understand the working of var filename = e.target.files[0].name. Please help me out, if you can.
$(document).ready(function() {
$('input[type="file"]').change(function(e) {
var fileName = e.target.files[0].name;
$('#choose').html(fileName);
});
});
Breaking the line e.target.files[0].name down in to sections:
e is the Event object passed to the jQuery event handler function as an argument.
target is the property which contains a reference to the element which raised the event
files is a collection of the files selected within the input type="file" control. If the control has the multiple attribute set on it, it's possible for there to be more than 1 file selected, in which case you would need a loop.
[0] retrieves only the first selected file from the files collection - in the same manner as you access an array by index.
name gets the filename of that file.

How to dynamically populate files in multiple file input

I'm using a JavaScript lib here to select multiple image and save them in database through a form, and when i edit the form i get the images from data and populate like this.
<script>
var upload = new FileUploadWithPreview('myUniqueUploadId', {
showDeleteButtonOnImages: true,
text: {
chooseFile: 'Įkelkite nuotrauką',
browse: 'naršyti',
selectedCount: 'Pasirinkti failai',
},
presetFiles: [
<?php
foreach($Workimages as $Workimg){
echo $website_url.'master_image/'.$Workimg.','
}
],
})
</script>
The Images are coming as Blob and are being populated but when i update the data in database the old images are disregard but the new selected images get uploaded. I also checked $_FILES['images']. it don't have my old image files.
I have also tried to used methods upload.cachedFilesArray.push and upload.addFiles() but i wasn't successful at that. Is there any other way to populate multiple file input?
I'm the author of this library.
It seems as though you've uncovered a problem with a Blob type being accepted by your PHP server. This may be something that I just never ran into before, because I feel like I've uploaded Blob types in the past to my PHP servers - but maybe I'm just imagining things and they've always been File types and that's why I never had any issue.
Regardless, to make your situation work in the meantime, I made a simple codepen that loops over the upload.cachedFileArray array and converts each Blob (or File) into a File type, and appends it to a new temp array that's ready for uploading. See the comments in the codepen for more.
At this point, you can just upload the new temp array and you'll be all set. In the future I'll look at making sure all the presetFiles are of the type File instead of Blob.

Jquery exporting table to csv hidden table cells

I need to be able to export a HTML table to CSV. I found a snippet somewhere; it works but not entirely how I want it to.
In my table (in the fiddle) I have hidden fields, I just use quick n dirty inline styling and inline onclicks to swap between what you see.
What I want with the export is that it selects the table as currently displayed. so only the td's where style="display:table-cell". I know how to do this in normal JS.
document.querySelectorAll('td[style="display:table-cell"])');
but how can I do this using the code I have right now in the exportTableToCSV function?
(sorry but the text in the fiddle is in dutch as its a direct copy of the live version).
The fiddle:
http://jsfiddle.net/5hfcjkdh/
In your grabRow method you can filter out the hidden table cells using jQuery's :visible selector. Below is an example
function grabRow(i, row) {
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th') won't work...
//Added :visisble to ignore hidden ones
var $cols = $row.find('td:visible');
if (!$cols.length) $cols = $row.find('th:visible');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}
Here's how i solved it. Decided to step away from a pure javascript solution to take processing stress off the client and instead handle it server side.
Because i already get the data from the database using a stored procedure i use this to just get the dataset again and convert it into an ViewExportModel so i have a TotalViewExport and a few trimmed variations (reuse most of them) based on a Selected variable i fill a different model.
Added to the excisting show function to update a Selected variable to keep track of the currently selected view.
When the user clicks Export table to excel it calls to the controller of the current page, IE. AlarmReport (so AlarmReportController) and i created the action ExportReports(int? SelectedView);
In addition i added CsvExport as a manager. This takes data results (so c# models/ iqueryables/ lists/ etc). and puts them into a Csv set. using the return type BinaryContent one can export a .csv file with this data.
The action ExportReports calls the stored procedure with the selectedview parameter. The result gets pumped into the correct model. this model is pumped into the CsvExport model as rows.
The filename is made based on the selected view + What object is selected + current date(yyyy-MM-dd). so for example "Total_Dolfinarium_2016-05-13". lets
lastly the action returns the .csv file as download using the BinaryContent Returntype and ExportToBytes from the CsvExport
The export part of this action is programmed like so(shortened to leave some checks out like multiple objects selected etc)(data and objectnames are gathred beforehand):
public ActionResult ExportCsv(CsvExport Data, string ObjectName, string Type){
var FileName = Type + "_" + ObjectName + "_" + DateTime.Now.ToString("yyyy/MM/dd");
return BinaryContent("text/csv", FileName + ".csv", Data.ExportToBytes());
}

Convert base64 image to file in javascript or how to pass a big base64 string with jquery ajax

This can't take any more of my time. I've tried to solve this a very long time now.
I will give you my whole scenario and then what the problem is.
I have this web site. On one page the user can choose between three image input types.
This is a radio button group:
o Twitter Logo
o Twitter Profile Picture
o Upload picture
If the user choose option 1 or 2, an img tag src is updated with a local-project file (http://localhost:9000/public/images/image.png) and this image src is stored in html5 Web Session Storage variable.
If the user choose option 3 he/she get to choose a file from their computer (a input type="file" appears under the radio group) and the img tag src is updated with this image.
This time, the src that I will store in the session variable won't be a path to the file (which I know is because of security reasons) but the src will be a base64 string. A really big one if the user choose a big image.
So now I have this image stored in the session variable, either a path to the image file included in the project folder or a base64 encoded image.
What I do now is to fetch this value from the session variable in JavaScript. I want to pass this image to my code on the server side. For making an actual image of it and uploading it to places, but that part isnt really necessary.
My problem is that in JavaScript, I can't pass this with a POST using $.ajax.
The base64 string is too big I think, and I can't figure out how I can convert it to something else, say a byte[].
How should I do?
I want to pass this image that the user choose to the server side for further process.
Then on the server side I want to convert it to an actual Image object, or BufferedImage.
Here's a code-block of how it looks now:
function gatherSessionValuesAndGenerateCode(userEmail) {
var email = userEmail;
var category = getSessionValue("category");
var itemName = getSessionValue("itemName");
var service = getSessionValue("service");
var accountName = getSessionValue("accountName");
var action = getSessionValue("action");
var imageType = getSessionValue("imageType");
var imageFile = getSessionValue("imageFile");
var expirationDate = getSessionValue("expirationDate");
$.ajax({
type: "POST",
url: "http://localhost:9000/quikkly/business/create/generate",
data: {
email: email,
category: category,
itemName: itemName,
service: service,
accountName: accountName,
action: action,
imageType: imageType,
imageFile: imageFile, //This is making me feel ill, don't know how to solve it.
expirationDate: expirationDate
},
success: function(response){console.log("Horayyy "+response)}
});
}
ok i got your point but what i am trying to say is may be your string contains 20K characters but i don't think it can be larger than 2-3 Mb and i hope your server settings allows you to post data of size of 2-3 MB.
Apart from this i think putting the image path name in base_64 is not a good idea.If you think someone can steel the data from your seesion then he/she can do any thing with your complete website concept.
Because any how a person can see the image path even when you display some image over web page.
Still if you think you don't want path in seesion you can keep it in some file in key-value pair or you can keep it in database.
OR you can do one more thing just keep the image file name in your seesion data & prepend the exact path when you want to use it internally over server side.

fine-uploader unique but ascending ID in filename on submit and cancel

this issue relates to Widen Fine-Uploader ( https://github.com/Widen/fine-uploader )
i got this multipart upload form. no autoupload. i want to upload a couple of images and safe them under an unique name for each image.
eg. you pick 4 images. upload via fine-upload. i already got a gallery id. all images should be saved under a filename using the gallery-id and an unique ascending number. like this:
1234-1.jpg
1234-2.jpg
1234-3.jpg
1234-4.jpg
sounds easy, but there are two problems:
the image-id needs to be ascending without skipping any one. That may happen, if you cancel (remove) a file before upload. so the image-id needs to be set up AFTER selecting all files OR it needs to fill up empty IDs on removing a file.
the order of the images must be strictly adhered to the order you choose files on input. the first image you pick, becomes 1234-1.jpg, the second one 1234-2.jpg ... so i'm not able to set the ID at the imageHandler script after reload. It would grab the first complete image that must not be the first image in order, because i use several simultaneous connections on upload.
I tried something like that:
.on('submitted', function(event, id, name) {
var picId = id+1;
$(this).fineUploader('setParams', {
'currentGid': 1234,
'picId':picId
});
})
or
params: {
fileNum: function() {
return $(this).attr('id');
}
}
or using a fileCount++ but nothing works like i need..
Your application sounds a bit brittle, and it is probably in your best interests to address that.
You'll simply need to maintain a map of your unique ids along with the ids maintained for each file by Fine Uploader. In your "submitted" handler, add a key/value pair to the map. In a "cancel" handler, adjust the items in the map appropriately. In an "upload" handler, call the "setParams" API method. Your parameters will by the gallery ID, the unique ID you've been tracking in your map for that specific file, and be sure to pass the id of the file as your last parameter to the "setParams" call. This lets Fine Uploader know that this parameter is only for that specific file.
Please see the callbacks documentation for more info.
Here's a code example:
var fileIds = [];
$('#myFineuploaderContainer').fineUploader({
//set your options here
})
.on('submitted', function(event, id, name) {
fileIds.push(id);
})
.on('cancel', function(event, id, name) {
var fileIdPosition = $.inArray(id, fileIds);
fileIds.splice(fileIdPosition, 1);
})
.on('upload', function(event, id, name) {
var params = {
currentGid: 1234,
picId: $.inArray(id, fileIds)
};
$(this).fineUploader('setParams', params, id);
});

Categories

Resources