Insert image in editor after upload - image

I've managed to upload images through drag & drop to a SP 2013 library by intercepting the paste and fileUploadrequest events (+ added mandatory headers and used /_api/web/getfolderbyserverrelativeurl(\'/sites/theSite/theLibrary\')/files/add(overwrite=true,%20url=\'aDynamicFilename.jpg\') as the request's URL).
The problem with this approach is that even if the image is uploaded, the image is not inserted in the editor (no error). I'm not setting config.uploadUrl for this approach.
Q#1: Is there any step which I should go through after the image is uploaded? Like telling the CKEDITOR instance to insert the image?
Later on, I've noticed that if I'm setting the config.uploadUrl to the same URL as I'm using above, the editor inserts successfully the image. The problem is that, from my trials, the config.uploadUrl is initialized together with the CKEDITOR instance (therefore, can't be assigned dynamically for each image, in case that multiple images are dragged and dropped on the editor).
Q#2: Is there another way to configure the uploadUrl or maybe some other config property that would allow the custom upload to work and insert the image in the editor?

Eventually made it work by following a similar approach as the on in this repo:
RyanSiu1995/ckeditor-ImageUploader
Use a FileReader and start loading the image when it's pasted to the
CKEditor
On the fileReader's onload event, create a img element in the
editor's document object with some opacity and with the fileReader's
Base64 string as the src
On the fileLoader's uploaded event, remove
the img and re-add it with the actual file's url (changing the src
attribute on the img was not triggering the editor's change event, which I was hooking into,so I chose to replace the whole element)
Here's the relevant section from the ckeditor-ImageUploader plugin:
fileDialog.on('change', function (e) {
var fileTools = CKEDITOR.fileTools,
uploadUrl = fileTools.getUploadUrl( editor.config, 'image' ),
file = e.target.files[0],
loader = editor.uploadRepository.create(file),
reader = new FileReader(),
notification,
img;
// verify
if (!/image/i.test(file.type)) {
notification = editor.showNotification( 'Please check the correct format.', 'warning' );
setTimeout(function() {
notification.hide()
}, 2000);
return false
}
loader.upload(uploadUrl);
// preview image
reader.readAsDataURL(e.target.files[0]);
reader.onload = function (e) {
img = editor.document.createElement('img');
img.setAttribute('src', e.target.result);
img.setStyle('opacity', 0.3);
editor.insertElement(img);
}
loader.on('uploaded', function(evt) {
editor.widgets.initOn(img, 'image', {
src: evt.sender.url
});
img.setAttribute('src', evt.sender.url);
img.setStyle('opacity', 1);
});
loader.on('error', function() {
img.$ && img.$.remove();
});
fileTools.bindNotifications(editor, loader);
// empty input
fileDialog[0].value = "";

Related

CKFinder 3: Moving Resized Image to a destination folder

I am using CKFinder 3 intergrated with CKEditor. Now, after resizing an Image and clicking on Choose Resized, I want to move/copy the resized image to another folder using javascript. I am able to get upto the following code.
CKFinder.start({
onInit: function (finder) {
finder.on('file:choose:resizedImage', function (event) {
var file = event.data.file;
var resizedData = file.get('imageResizeData');
var resized = file.get('imageResizeData').get('resized');
// Need help here to move the resized image to another folder.
});
}
});
NOTE: I am using ASP.NET Connector.
You can use command:send request to send CopyFiles request:
https://docs-old.ckeditor.com/ckfinder3/#!/api/CKFinder.Application-request-command_send
Parameters taken by CopyFiles can be found here:
https://docs-old.ckeditor.com/ckfinder3-net/commands.html#command_copyfiles

CKEditor: Modifying view without changing data

I have content that references Images by ID within a placeholder (e.g. "$m(12345)" ). I have a REST call that will return an img-tag for the placeholder.
I would like CKEditor to display the image when the content is opened in editor, or a placeholder is inserted. But I want the placeholder to remain in the content (including when switching to the Source view)
I've tried to do this by adding a rule to the dataFilter:
CKEDITOR.on('instanceLoaded', function(ckeditor){
var mediaPlaceholderRegex = /\$m\(.*\)/;
ckeditor.editor.dataProcessor.dataFilter.addRules({
text: function( text, node ) {
return text.replace( mediaPlaceholderRegex, function( match ) {
var params = "placeholder="+match;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
return xhttp.responseText;
} );
}
});
});
It does the job of replacing the placeholder with the image tag, but the img-tag is also there when switching to the source view.
Is there an easy way to only apply a filter to the wysiwyg view.
The only way I see is to add a htmlFilter that would revert the img-tag back to a placeholder.
Is there an easy way to only apply a filter to the wysiwyg view. The only way I see is to add a htmlFilter that would revert the img-tag back to a placeholder.
Good thinking. Either that of if you don't want your images to be removed/fetched from the server on every mode change, you can for example put your placeholder into the data- attribute for the image tag. It all depends on your use case but the bottom line is that dataFilter is used when you load data into the editor and htmlFilter when you get data from the editor (same methods are used when getting data and switching to source mode so htmlFilter applies here).

How to refresh image.src dataurl, prevent cache?

I have the following code that loads an image that I choose from files. It loads and draws it to a canvas, but if I make a change the the image file via an image editor, and then reload it- it doesn't refresh and show the changes(it uses the cached version)..
How can I get it to refresh??
var reader = new FileReader();
reader.onload = function(event){
img[num] = new Image();
img[num].onload = function () {
//handle image stuff
}
img[num].src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
Sorry, was an issue with the input file change event. Since the filename wasn't different, it wasn't calling the change event
If I add the line to clear the value, it works.
$( "#imageReplacer" ).on("change", function( event ){
replaceImage(event);
$(this).val('');
}).hide();

fineuploader - Read file dimensions / Validate by resolution

I would like to validate by file dimensions (resolution).
on the documentation page there is only information regarding file name and size, nothing at all in the docs about dimensions, and I also had no luck on Google.
The purpose of this is that I don't want users to upload low-res photos to my server. Thanks.
As Ray Nicholus had suggested, using the getFile method to get the File object and then use that with the internal instance object qq.ImageValidation to run fineuploader's validation on the file. A promise must be return because this proccess is async.
function onSubmit(e, id, filename){
var promise = validateByDimensions(id, [1024, 600]);
return promise;
}
function validateByDimensions(id, dimensionsArr){
var deferred = new $.Deferred(),
file = uploaderElm.fineUploader('getFile', id),
imageValidator = new qq.ImageValidation(file, function(){}),
result = imageValidator.validate({
minWidth : dimensionsArr[0],
minHeight : dimensionsArr[1]
});
result.done(function(status){
if( status )
deferred.reject();
else
deferred.resolve();
});
return deferred.promise();
}
Remained question:
Now I wonder how to show the thumbnail of the image that was rejected, while not uploading it to the server, the UI could mark in a different color as an "invalid image", yet the user could see which images we valid and which weren't...
- Update - (regarding the question above)
While I do not see how I could have the default behavior of a thumbnail added to the uploader, but not being uploaded, but there is a way to generate thumbnail manually, like so:
var img = new Image();
uploaderElm.fineUploader("drawThumbnail", id, img, 200, false);
but then I'll to create an item to be inserted to qq-upload-list myself, and handle it all myself..but still it's not so hard.
Update (get even more control over dimensions validation)
You will have to edit (currently) the qq.ImageValidation function to expose outside the private function getWidthHeight. just change that function deceleration to:
this.getWidthHeight = function(){
Also, it would be even better to change the this.validate function to:
this.validate = function(limits) {
var validationEffort = new qq.Promise();
log("Attempting to validate image.");
if (hasNonZeroLimits(limits)) {
this.getWidthHeight().done(function(dimensions){
var failingLimit = getFailingLimit(limits, dimensions);
if (failingLimit) {
validationEffort.failure({ fail:failingLimit, dimensions:dimensions });
}
else {
validationEffort.success({ dimensions:dimensions });
}
}, validationEffort.success);
}
else {
validationEffort.success();
}
return validationEffort;
};
So you would get the fail reason, as well as the dimensions. always nice to have more control.
Now, we could write the custom validation like this:
function validateFileDimensions(dimensionsLimits){
var deferred = new $.Deferred(),
file = this.holderElm.fineUploader('getFile', id),
imageValidator = new qq.ImageValidation(file, function(){});
imageValidator.getWidthHeight().done(function(dimensions){
var minWidth = dimensions.width > dimensionsLimits.width,
minHeight = dimensions.height > dimensionsLimits.height;
// if min-width or min-height satisfied the limits, then approve the image
if( minWidth || minHeight )
deferred.resolve();
else
deferred.reject();
});
return deferred.promise();
}
This approach gives much more flexibility. For example, you would want to have different validation for portrait images than landscape ones, you could easily identify the image orientation and run your own custom code to do whatever.

Trigger effect after changing src attribute of img tag

Im using this code to change the src attribute of an image tag (using prototype and scriptaculous):
new Effect.Fade("images",{afterFinish:
function()
{
$("detail").setAttribute("src", "img/02.jpg");
new Effect.Appear("images",{duration:0.8});
}
});
Where "images" is the container (a div) and "detail" is the img tag
The result is the current image fades, appears and then the new image suddenly shows.
My question is, how can i check the new image is fully loaded by the browser to trigger the Effect.Appear after?
Is there another way to do this?
Images have an onload event you can hook up to:
$("detail").onload = function()
{ do_stuff(); } // Remember to do this BEFORE changing the src
In my experience, it is a bit flaky sometimes (at times doesn't seem to get executed). It would be better to pre-load the image and allow this effect only after the full document has loaded (onload instead of dom:load or ready).
Replace
new Effect.Appear("images",{duration:0.8});
with
Event.observe("detail", 'load', function() {
new Effect.Appear("images",{duration:0.8});
Event.stopObserving('detail', 'load');
});
To tell the user that you are loading the image, you could set a css background to the image, with a spinnging circle or whatever suits.

Resources