I'm trying to set request headers of Kendo UI Editor's Upload Url and ThumbnailUrl for authorization.
$(document).on("change", "input[name=file]", function (e) {
$("#Template").data("kendoEditor").options.imageBrowser.transport.uploadUrl.beforeSend = function (xhr) {
xhr.setRequestHeader("Authorization", GetToken());
};
});
I've tried this one. Anybody knows how to set it? Kendo UI Upload have its event for upload and on the back-end Editor is also using Kendo UI Upload.
Help will be appreciated. Thanks
I got an answer from telerik support. There is no event for upload. But we can bind it in execute event. here is the code
function onExecute(e) {
if (e.name == "insertimage") {
setTimeout(function () {
var imagebrowser = $("[data-role=imagebrowser]").data("kendoImageBrowser");
imagebrowser.upload.bind("upload", function (e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function (e) {
if (xhr.readyState === 1 /* OPENED */) {
xhr.setRequestHeader("Authorization", GetToken());
}
});
}
});
}, 0);
}
}
There isn't a way to set a header for the thumbnail request. So I've achieved this functionality by sending user id as a query string in Thumbnail request.
thumbnailUrl: hostHeaderUrl + "api/ImageBrowser/Thumbnail?userId=" + currUserId
Hopefully my answer will help.
Related
I’m having a weird issue on a Webflow site I’m building for a radio station and can’t find a solution anywhere so I thought I’d try to ask you for some help.
I have this ajax page loader code to allow for continuous playback of the radio stream while browsing the site. That code works EXCEPT it breaks all other custom code when clicking on anything. There are no errors in the console and I have tried to move the code between the different code editors but the problem persists. I don’t know if the code clashes with Webflow somehow but the code is pure vanilla javascript so this issue is driving me mad.
If someone might have an idea of what the problem is please feel free to share your solution. I’d really appreciate it! Here’s the ajax code:
let main = document.querySelector('main');
window.addEventListener('popstate', function (e) {
requestPage(e.state, false);
});
function requestPage(url, push) {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
main.innerHTML = xhr.responseText;
var title = (/<title>(.*?)<\/title>/m).exec(xhr.responseText)[1];
var headers = document.querySelectorAll('.header');
var footers = document.querySelectorAll('.footer');
if (headers.length > 1) {
headers[1].remove();
};
if (footers.length > 1) {
footers[1].remove();
};
attachLinkClickHandlers(main);
document.title = title;
if (push)
history.pushState(url, document.title, url);
}
};
xhr.open('get', url, true);
xhr.send();
}
function attachLinkClickHandlers(parent) {
let links = parent.querySelectorAll('a:not([href^="http"])');
[].forEach.call(links, function (link) {
link.addEventListener('click', function (e) {
requestPage(link.href, true);
e.preventDefault();
return false;
});
});
}
attachLinkClickHandlers(document);
history.replaceState(location.href, document.title, location.href);
Here's a link to the live site
and to the read-only
I have a tricky situation :
There is UI which just has a button. On button click I process a PowerPoint document in the server (I add some relevant content to the slide) and then download it to the client system.
Now when the user clicks the download button, I show a small animated gif saying "processing", but when the PowerPoint file downloads into the client system I am not able to hide or disable the "processing image".
This is the Serverside Code:
HttpContext.Current.Response.ContentType = "APPLICATION /OCTET-STREAM";
String Header = "Attachment; Filename=" + FileName;
HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
//for the server
//for normal
System.IO.FileInfo Dfile = new System.IO.FileInfo(PPTPath);
HttpContext.Current.Response.WriteFile(Dfile.FullName);
This is the Client Side Code :
ShowProcessMessage = function(PanelName)
{
document.getElementById(PanelName).hidden = "";
document.getElementById("Image1").style.visibility = "visible";
return true; //Returns the control to the Server click event
}
Can anyone give some Ideas on how to implement?
Possible solution is do client side ajax call.
use beforeSend to show spinner and complete to hide spinner (complete triggers on succes of failure)
$.ajax({
url: linktoPdf
, beforeSend: function (xhr) { $('#idOfSpinner').addClass("showSpinner"); }
, complete: function () { $('#idOfSpinner').removeClass("showSpinner"); }
, success: function (response) { /*your code here */ }
, error: function () { /*your code here */ }
});
I have a basic HTML form that submits normally, no ajax at all. This form submits to the same file using regular post. I don't use AJAX because the form has 12 text fields and a minimum of 1 image but possibility of up to 26 images and ajax can't do both forms and images at once, I have to save to a DB and it's a lot of extra work over AJAX.
The problem is I need to track form upload progress somehow. Most programmers know to look in the lower left or right corner of their browsers to see form submission progress. But most people don't know this.
So I want to display a progress bar. The problem is all progress bars I have found use XHR requests by ajax. Since the form isn't ajax I can't seem to find a way to track the progress.
So is there a way to intercept the browsers internal submission progress to see the percentage of upload completed for the form?
EDIT
I've tried the following code at the start of the page but it doesn't work. I guess because either XHR is for AJAX or the browser has it's own that needs Hijacking, but I have no clue what that would be called or how to get to it if so:
xhr = new XMLHttpRequest();
xhr.upload.addEventListener( "progress", function ( evt )
{
if( evt.lengthComputable )
{
var progressPercent = ( evt.loaded / evt.total ) * 100;
console.log( value );
}
}, false );
This is some type of progressive enhancement i sometimes use. It will still make an ajax request but in the most transparent way as possible both for the user and the developer.
The key is to post the exact same data as posted by a regular form thanks to FormData, and to replace the whole document when we receive the full page reponse form the server. This is an untested simplified version :
function enhanceFormWithUploadProgress(form, progress) {
//form : the HTML form element to enhance.
//progress : an HTML element that will display upload progress.
//testing browser support. if no support for the required js APIs, the form will just be posted naturally with no progress showing.
var xhr = new XMLHttpRequest();
if (!(xhr && ('upload' in xhr) && ('onprogress' in xhr.upload)) || !window.FormData) {
return;
}
form.addEventListener('submit', function(e) {
//prevent regular form posting
e.preventDefault();
xhr.upload.addEventListener('loadstart', function(event) {
//initializing the progress indicator (here we're displaying an element that was hidden)
progress.style.display = 'block';
}, false);
xhr.upload.addEventListener('progress', function(event) {
//displaying the progress value as text percentage, may instead update some CSS to show a bar
var percent = (100 * event.loaded / event.total);
progress.innerHTML = 'Progress: ' + percent.toFixed(2) + '%';
}, false);
xhr.upload.addEventListener('load', function(event) {
//this will be displayed while the server is handling the response (all upload data has been transmitted by now)
progress.innerHTML = 'Completed, waiting for response...';
}, false);
xhr.addEventListener('readystatechange', function(event) {
if (event.target.readyState == 4 && event.target.responseText) {
//we got a response from the server and we're replacing the whole current document content with it, simulating a page reload
var newDocument = document.open('text/html', 'replace');
newDocument.write(event.target.responseText);
newDocument.close();
} else {
throw new Error('Error in the response.');
}
}, false);
//posting the form with the same method and action as specified by the HTML markup
xhr.open(this.getAttribute('method'), this.getAttribute('action'), true);
xhr.send(new FormData(this));
});
};
HTML:
<form method="post">
<button type="submit">Submit</button>
</form>
JavaScript:
/*
Show a progress element for any form submission via POST.
Prevent the form element from being submitted twice.
*/
(function (win, doc) {
'use strict';
if (!doc.querySelectorAll || !win.addEventListener) {
// doesn't cut the mustard.
return;
}
var forms = doc.querySelectorAll('form[method="post"]'),
formcount = forms.length,
i,
submitting = false,
checkForm = function (ev) {
if (submitting) {
ev.preventDefault();
} else {
submitting = true;
this.appendChild(doc.createElement('progress'));
}
};
for (i = 0; i < formcount; i = i + 1) {
forms[i].addEventListener('submit', checkForm, false);
}
}(this, this.document));
Demo: http://jsfiddle.net/jsbo6yya/
Credit: https://gist.github.com/adactio/9315750
I'm wondering if there's any way to make Dropzone.js (http://dropzonejs.com) work with a standard browser POST instead of AJAX.
Some way to inject the inputs type=file in the DOM right before submit maybe?
No. You cannot manually set the value of a <input type='file'> for security reasons. When you use Javascript drag and drop features you're surpassing the file input altogether. Once a file is fetched from the user's computer the only way to submit the file to the server is via AJAX.
Workarounds: You could instead serialize the file or otherwise stringify it and append it to the form as a string, and then unserialize it on the server side.
var base64Image;
var reader = new FileReader();
reader.addEventListener("load", function () {
base64Image = reader.result;
// append the base64 encoded image to a form and submit
}, false);
reader.readAsDataURL(file);
Perhaps you're using dropzone.js because file inputs are ugly and hard to style? If that is the case, this Dropzone.js alternative may work for you. It allows you to create custom styled inputs that can be submitted with a form. It supports drag and drop too, but with drag and drop you cannot submit the form the way you want. Disclaimer: I am author of aforementioned library.
So, if I understood correctly you want to append some data (input=file) before submit your form which has dropzone activated, right?
If so, I had to do almost the same thing and I got it through listening events. If you just upload one file, you should listen to "sending" event, but if you want to enable multiple uploads you should listen to "sendingmultiple". Here is a piece of my code that I used to make this work:
Dropzone.options.myAwesomeForm = {
acceptedFiles: "image/*",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
init: function() {
var myDropzone = this;
[..some code..]
this.on("sendingmultiple", function(files, xhr, formData) {
var attaches = $("input[type=file]").filter(function (){
return this.files.length > 0;
});
var numAttaches = attaches.length;
if( numAttaches > 0 ) {
for(var i = 0; i < numAttaches; i++){
formData.append(attaches[i].name, attaches[i].files[0]);
$(attaches[i]).remove();
}
}
});
[..some more code..]
}
}
And that's it. I hope you find it helpful :)
PS: Sorry if there's any grammar mistakes but English is not my native language
For future visitors
I've added this to dropzone options:
addedfile: function (file) {
var _this = this,
attachmentsInputContainer = $('#attachment_images');
file.previewElement = Dropzone.createElement(this.options.previewTemplate);
file.previewTemplate = file.previewElement;
this.previewsContainer.appendChild(file.previewElement);
file.previewElement.querySelector("[data-dz-name]").textContent = file.name;
file.previewElement.querySelector("[data-dz-size]").innerHTML = this.filesize(file.size);
if (this.options.addRemoveLinks) {
file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\">" + this.options.dictRemoveFile + "</a>");
file._removeLink.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
if (file.status === Dropzone.UPLOADING) {
return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function () {
return _this.removeFile(file);
});
} else {
if (_this.options.dictRemoveFileConfirmation) {
return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function () {
return _this.removeFile(file);
});
} else {
return _this.removeFile(file);
}
}
});
file.previewElement.appendChild(file._removeLink);
}
attachmentsInputContainer.find('input').remove();
attachmentsInputContainer.append(Dropzone.instances[0].hiddenFileInput).find('input').attr('name', 'files');
return this._updateMaxFilesReachedClass();
},
This is default implementation of dropzone's addedfile option with 3 insertions.
Declared variable attachmentsInputContainer. This is invisible block. Something like
<div id="attachment_images" style="display:none;"></div>
Here I store future input with selected images
Then in the end of function remove previously added input(if any) from block and add new
attachmentsInputContainer.find('input').remove();
attachmentsInputContainer.append(Dropzone.instances[0].hiddenFileInput).find('input').attr('name', 'files');
And now, when you send form via simple submit button, input[name="files"] with values will be send.
I've made this hack because I append files to post that maybe not created yet
This is what I used for my past projects,
function makeDroppable(element, callback) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('multiple', true);
input.style.display = 'none';
input.addEventListener('change', triggerCallback);
element.appendChild(input);
element.addEventListener('dragover', function(e) {
e.preventDefault();
e.stopPropagation();
element.classList.add('dragover');
});
element.addEventListener('dragleave', function(e) {
e.preventDefault();
e.stopPropagation();
element.classList.remove('dragover');
});
element.addEventListener('drop', function(e) {
e.preventDefault();
e.stopPropagation();
element.classList.remove('dragover');
triggerCallback(e);
});
element.addEventListener('click', function() {
input.value = null;
input.click();
});
function triggerCallback(e) {
var files;
if(e.dataTransfer) {
files = e.dataTransfer.files;
} else if(e.target) {
files = e.target.files;
}
callback.call(null, files);
}
}
i'm trying to login into the site with the following javascript. But, i'm loading only the complete page. I'm developing windows 8 app
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/home/home.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
// TODO: Initialize the page here.
document.getElementById("bt_login").addEventListener("click", login, false);
}
});
})();
function login() {
var xhrDiv = document.getElementById("xhrReport");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = dataLoaded;
xhr.open("POST", "http://www.160by2.com", true, <username>, <password>);
xhr.send();
function dataLoaded() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// OK
xhrDiv.innerHTML = window.toStaticHTML("response:" + xhr.responseText);
} else {
// not OK
xhrDiv.innerText = "failure";
}
}
};}
I want to dsiplay in xhrdiv.innerHTML as "LOGIN SUCCESS" or "LOGIN ERROR"
EDIT:
I tried the following code:
iframe = document.getElementById("ifra_op");
iframe.setAttribute("src", "http://www.160by2.com/index");
document.getElementById("op").appendChild(iframe);
iframe.contentWindow.document.getElementById("MobileNoLogin") = "<mobno>";
iframe.contentWindow.document.getElementById("LoginPassword") = "<pass>;
iframe.contentWindow.document.getElementsByName("LoginForm").click();
But, there is an error. It says "Javascript run time error:math is undefined"
"math" comes from the website. I don't know how to handle this. Also, the permission is denied. Why is that so?
You need to make sure you have a service (something like a web service) in the remote server to process the request.
In here what you can do is.
Create an iframe and set the src to 160by2;
Access the webpage using iframe.contentwindow, inject your code to fill up the forms and trigger the submit button.
Parse the received html to verify your login.
Use jquery , makes life easier.
var iframe = $("#ifra_op");
$(iframe).attr("src", "http://www.160by2.com/index");
$(iframe).attr("onload","submitForm();");
function submitForm(){
$(iframe.contentWindow.document).find("#MobileNoLogin").val("9999");
$(iframe.contentWindow.document).find("#LoginPassword").val("pass");
$('#button').click();
}