I am looking for sample code that would show how to set validation on the Html.Telerik().Upload() function so that the user can only upload .jpg files. I'd like to support just .jpg files.
Does anyone have any good examples or websites that I could use?
Unfortunately, filtering the extensions is not possible using Html.Telerik().Upload() due to the way browsers implement the <input type="file" />.
Source:
http://www.telerik.com/community/forums/aspnet-ajax/upload/how-to-filter-out-unwanted-file-types-radupload.aspx
But, there is an alternative to do that with html and javascript:
HTML
<input name="fileToUpload" type="file" onchange="check_file()" >
javascript
function check_file(){
str=document.getElementById('fileToUpload').value.toUpperCase();
suffix=".JPG";
suffix2=".JPEG";
if(!(str.indexOf(suffix, str.length - suffix.length) !== -1||
str.indexOf(suffix2, str.length - suffix2.length) !== -1)){
alert('File type not allowed,\nAllowed file: *.jpg,*.jpeg');
document.getElementById('fileToUpload').value='';
}
}
Source: https://stackoverflow.com/a/6788623/1304064
Please see the following Code. This code only accept jpeg/jpg, png format image. Also image size is restricted to 100KB.
#(Html.Telerik().Upload()
.Name("EmployeeImageUpload")
.Multiple(false)
.Async(async => async
.Save("SaveEmployeeImage", "Employee")
.AutoUpload(false)
)
.ClientEvents(events => events
.OnLoad("onLoad")
.OnSelect("onSelect")
.OnSuccess("onSuccess")
)
)
<script type="text/javascript">
function onLoad(e) {
$(this).find("input").attr("accept", "image\/jpeg,image\/jpg,image\/png");
}
function onSelect(e) {
if (e.files[0].size > 102400) {
alert('Image Size Should Be <= 100KB');
e.preventDefault();
return false;
}
var ext =e.files[0].extension.toLowerCase();
if ($.inArray(ext, ['.jpeg', '.jpg', '.png']) == -1) {
alert('Only Supported Extension are jpeg/jpg, png');
e.preventDefault();
return false;
}
return true;
}
</script>
Related
I have using the template code like:
{snippetArea wrapper}
{control addFormControl}
{/snippetArea}
and in addFormControl component code is like:
{snippet clientSnippet}
......
{/snippet}
I am using ajax with method presenter method:
public function handleClientChange(){
$this['addFormControl']['addForm']['consignment_client']->setValue("test");
$this->redrawControl('wrapper');
$this->redrawControl('clientSnippet');
}
But it is not redraw the snippet snippet id is snippet-addFormControl-clientSnippet. Please help me to fix it.
I dont think you can call $this->redrawControl('clientSnippet'); in presenter and expect to redraw component. You should call this in the component.
Something like $this['addFormControl']->redrawControl('clientSnippet');
this is how you can do it.
In my latest project i was doing something quite similiar, it's pretty simple tho.
For Nette I use this Ajax: https://github.com/vojtech-dobes/nette.ajax.js
.latte file:
<input type="text" id="search-car" data-url="{plink refreshCars!}">
{snippet carlist}
{foreach $cars as $car}
{var $photo = $car->related('image')->fetch()}
{if $photo}
<img src="{plink Image:image $photo->filename}"/>
{/if}
</a>
{/foreach}
{/snippet}
Notice the '!' at the end of the text input. It's tells Nette to look after the handle function.
The presenter:
public function handleRefreshCars()
{
$this->redrawControl('carlist');
}
public function renderDefault($foo = null)
{
if ($foo === null || $foo === '') {
$this->template->cars = array();
} else {
$this->template->cars = $this->carDao->getFiltered($foo);
}
}
And JS:
function callFilterAjax(url, data) {
$.nette.ajax({
url: url,
data: data
});
}
$("#search-contract-car").on('load focus focusout change paste keyup', function () {
callFilterAjax($(this).data('url'), {"foo": $(this).val()});
});
This should be it. I hope you find this useful
I am working on a Magento store trying to code a widget's javascript layer with the help of Prototype js framework.
In my grid.js file AJAX call is setup like that:
loadTabContent: function(tab, tabType){
if(tab === undefined || tabType === undefined){
return this;
}
entityId = tab.id.split('-')[3];
request = new Ajax.Request(
this.tabContentLoadUrl,
{
method:'get',
onSuccess: this.onTabContentLoad.bind(tab),
onFailure: this.ajaxFailure.bind(this),
evalJS: true,
parameters: {
id: entityId,
type: tabType
}
}
);
}
Below is the success handler:
onTabContentLoad: function(transport){
if(transport && typeof transport.responseText !== undefined){
try{
response = transport.responseText;
}catch (e) {
console.log('PARSE ERROR', e);
response = {};
}
entityId = this.id.split('-')[3];
tabType = this.id.split('-')[1];
if(response && $('tab-' + tabType + '-' + entityId + '-contents')){
$('tab-' + tabType + '-' + entityId + '-contents').update(response);
}
}
},
The content for the div is getting updated correctly by the AJAX call but there is some inline JS in response which is not working.
I can't even see that javascript snippet in Elements tab(chrome developer tool)
Below is the code that handles the AJAX request on server side:
public function renderTabContentAction()
{
$entityId = Mage::app()->getRequest()->getParam('id');
if( ! $entityId){
$this->getResponse()->setHeader('HTTP/1.0', '400', true);
$this->getResponse()->setBody('Invalid parameters provided.');
}
$tabType = Mage::app()->getRequest()->getParam('type');
if( ! $tabType){
$this->getResponse()->setHeader('HTTP/1.0', '400', true);
$this->getResponse()->setBody('Invalid parameters provided.');
}
Mage::register('current_entity_id', $entityId);
Mage::register('current_tab_type', $tabType);
$tabHtml = $this->_getTabsHtml($entityId, $tabType);
$this->getResponse()->setHeader('HTTP/1.0', '200', true);
$this->getResponse()->setBody($tabHtml);
}
Below is the response that gets passed to onTabContentLoad AJAX handler:
<div class="vertical-tabs">
<div class="tabs">
<div class="tab" id="tab-vertical-137-2441">
<input type="radio" id="label-vertical-product-tab-137-2441" name="product-tab-group-137">
<label class="tabs-label" for="label-vertical-product-tab-137-2441">PG-10ml</label>
<div class="content" id="tab-vertical-137-2441-contents">
</div>
</div>
<div class="tab" id="tab-vertical-137-2442">
<input type="radio" id="label-vertical-product-tab-137-2442" name="product-tab-group-137">
<label class="tabs-label" for="label-vertical-product-tab-137-2442">PG-15ml</label>
<div class="content" id="tab-vertical-137-2442-contents">
</div>
</div>
</div>
</div>
<script type="text/javascript">
bulkOrderGrid.initVerticalTabs();
bulkOrderGrid.activateTab('2441', 'VERTICAL');
</script>
You can see that the SCRIPT tags are there in the response. Its just when the content gets updated using Element.update function it strips off the SCRIPT tags. That's what I can understand so far.
NOTE:
I have also used Ajax.Updater along with evalScripts:true and Ajax.Request along with evalJS:true.
Got stuck here. Any help would be much appreciated.
UPDATES:
Since I am using Element.update function to refresh the section. The source of the problem is this part of the code in prototype.js around line no. 2048. I can see its getting executed in js debugger. It does evaluates the js code but also removes the SCRIPT tags from the source. Commenting out stripScripts works fine.
else {
element.innerHTML = content.stripScripts();
}
content.evalScripts.bind(content).defer();
I think your problem is that
the Ajax response is passed through String#evalScripts() but the context is not the global context so instead of your script block do this
<script type="text/javascript">
window.bulkOrderGrid.initVerticalTabs();
window.bulkOrderGrid.activateTab('2441', 'VERTICAL');
</script>
if that doesnt fix it - than you can directly run transport.responseText.evalScripts() but you still need the window. in your script block to resolve the scope of the variables.
You are correct Element.update() remove script tag. you should use
Element.innerHTML
I've created validation rules for image uploading as follows.
$this->form_validation->set_rules('display_photo', 'Display Photo', 'callback_file_required|callback_file_size_max[1000]');
In controller I've included callback function as follows.
public function file_required($display_photo) {
if($_FILES[$display_photo]['size'] == 0) {
$this->form_validation->set_message('file_required', 'Upload a file.');
return false;
}
return true;
}
public function file_size_max($display_photo, $max_size) {
if($_FILES[$display_photo]['size'] > $max_size) {
$this->form_validation->set_message('file_size_max', 'This file exceeds max size.');
return false;
}
return true;
}
Only first rule is executing but not second rule. Please help me to find out the solution.
You should pass the file size limit in the config not in the validation rule.
Can u please paste the function or method that performs the upload ?
Not sure if you can use two callbacks on a single field when validation forms in CI. In any case you don't need to check the size to see if a file was uploaded. Use error code '4'
Solutions:
Check if the file was uploaded with if($_FILES[$display_photo]['error'] !== 4) // Error code 4 means no file was uploaded. So if it's not 4 then you have a file.
If you want to do multiple checks you can put them both in one single callback
$this->form_validation->set_rules('display_photo', 'Display Photo', 'callback_file_required_with_validation');
public function file_required_with_validation($display_photo) {
$max_size=1000;
if($_FILES[$display_photo]['size'] == 0) {
$this->form_validation->set_message('file_required', 'Upload a file.');
return false;
}
if($_FILES[$display_photo]['size'] > $max_size) {
$this->form_validation->set_message('file_size_max', 'This file exceeds max size.');
return false;
}
return true;
}
Pretty sure you need double underscore after 'callback' in your validation definition...
$this->form_validation->set_rules('display_photo', 'Display Photo', 'callback__file_required|callback__file_size_max[1000]');
One way - You can validate with JS before uploading the file:
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
//Submit form
} else {
//Prevent default and display error
evt.preventDefault();
}
}, false);
</script>
Original Question is here
But if you want validate at server side, then server until does't know whenever we upload the file.
I am using ASP.NET MVC Telerik editor in my project , the telerik editor doesn't support PDF upload functionality, well it supports image upload, is there a way I can include PDF upload functionality or have anyone tried to do something like that?
My settings:
#(Html.Telerik().Editor().Name(clientId)
/*.Encode(false) weird. Settings "Encode(false)" doesn't work on category & product details page
Now we have to manually decode values*/
.Value(Model)
.Tools(tools => tools
.Custom(settings => settings.HtmlAttributes(new { #class = "t-html", onclick = "viewRichHtmlEditorSource" + random + "(event)", title="Edit HTML" })))
.FileBrowser(browser => browser.Browse("Browse", "ImageBrowser")
.Thumbnail("Thumbnail", "ImageBrowser")
.Upload("Upload", "ImageBrowser")
.DeleteFile("DeleteFile", "ImageBrowser")
.DeleteDirectory("DeleteDirectory", "ImageBrowser")
.CreateDirectory("CreateDirectory", "ImageBrowser")))
How to add your suggested functionality within it?
Yes it does support pdf, i'm using it for pdf and it works just fine.
What you have to look out for is the SIZE of the file, you have to check and make sure it's not over 5MB big
Here is a sample of what I'm using:
<div class="editor-field">
#Html.TextBoxFor(model => model.NewFileName)
#(Html.Telerik().Upload()
.Name("attachment")
.Multiple(false)
.ClientEvents(events => events.OnSelect("onSelect"))
)
</div>
The onSelect script:
function onSelect(e) {
if (e.files[0].size > 5000000) {
alert('The file size is too large for upload');
e.preventDefault();
return false;
}
// Array with information about the uploaded files
var files = e.files;
var ext = $('#attachment').val().split('.').pop().toLowerCase();
if ($.inArray(ext, ['pdf']) == -1) {
alert('This type of file is restricted from being uploaded due to security reasons');
e.preventDefault();
} else {
$("#NewFileName").val(files[0].name);
}
return false;
}
The Controller action must receive the attachement in the signature like so:
public ActionResult EditFile(HttpPostedFileBase attachment) {
...
}
I'm writing a sidebar extension for Firefox and need a way to get the URL of the current page so I can check it against a database and display the results. How can I do this?
I stumbled over this post while looking for an answer to the same question.
Actually I think it's as easy as
alert(window.content.location.href)
See also https://developer.mozilla.org/en/DOM/window.content
window.top.getBrowser().selectedBrowser.contentWindow.location.href;
might work, otherwise I think you need to use:
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
mainWindow.getBrowser().selectedBrowser.contentWindow.location.href;
This seems to work fine for me
function getCurrentURL(){
var currentWindow = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var currBrowser = currentWindow.getBrowser();
var currURL = currBrowser.currentURI.spec;
return currURL;
}
https://developer.mozilla.org/En/Working_with_windows_in_chrome_code
If you need to access the main browser from the code running in a sidebar, you'll something like what Wimmel posted, except the last line could be simplified to
mainWindow.content.location.href
(alternatively you could use 's API returning an nsIURI).
Depending on your task, it might make sense to run the code in the browser window instead (e.g. in a page load handler), then it can access the current page via the content shortcut and the sidebar via document.getElementById("sidebar").contentDocument or .contentWindow.
If you need only domain and subdomain;
Usage;
PageDomain.getDomain(); // stackoverflow.com
PageDomain.getSubDomain(); // abc.stackoverflow.com
Code;
PageDomain = {
getDomain : function() {
var docum = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var domain = PageDomain.extractDomain(new String(docum.location));
return domain;
},
getSubDomain : function() {
var docum = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var subDomain = PageDomain.extractSubDomain(new String(docum.location));
return subDomain;
},
extractDomain: function(host) {
var s;
// Credits to Chris Zarate
host=host.replace('http:\/\/','');
host=host.replace('https:\/\/','');
re=new RegExp("([^/]+)");
host=host.match(re)[1];
host=host.split('.');
if(host[2]!=null) {
s=host[host.length-2]+'.'+host[host.length-1];
domains='ab.ca|ac.ac|ac.at|ac.be|ac.cn|ac.il|ac.in|ac.jp|ac.kr|ac.nz|ac.th|ac.uk|ac.za|adm.br|adv.br|agro.pl|ah.cn|aid.pl|alt.za|am.br|arq.br|art.br|arts.ro|asn.au|asso.fr|asso.mc|atm.pl|auto.pl|bbs.tr|bc.ca|bio.br|biz.pl|bj.cn|br.com|cn.com|cng.br|cnt.br|co.ac|co.at|co.il|co.in|co.jp|co.kr|co.nz|co.th|co.uk|co.za|com.au|com.br|com.cn|com.ec|com.fr|com.hk|com.mm|com.mx|com.pl|com.ro|com.ru|com.sg|com.tr|com.tw|cq.cn|cri.nz|de.com|ecn.br|edu.au|edu.cn|edu.hk|edu.mm|edu.mx|edu.pl|edu.tr|edu.za|eng.br|ernet.in|esp.br|etc.br|eti.br|eu.com|eu.lv|fin.ec|firm.ro|fm.br|fot.br|fst.br|g12.br|gb.com|gb.net|gd.cn|gen.nz|gmina.pl|go.jp|go.kr|go.th|gob.mx|gov.br|gov.cn|gov.ec|gov.il|gov.in|gov.mm|gov.mx|gov.sg|gov.tr|gov.za|govt.nz|gs.cn|gsm.pl|gv.ac|gv.at|gx.cn|gz.cn|hb.cn|he.cn|hi.cn|hk.cn|hl.cn|hn.cn|hu.com|idv.tw|ind.br|inf.br|info.pl|info.ro|iwi.nz|jl.cn|jor.br|jpn.com|js.cn|k12.il|k12.tr|lel.br|ln.cn|ltd.uk|mail.pl|maori.nz|mb.ca|me.uk|med.br|med.ec|media.pl|mi.th|miasta.pl|mil.br|mil.ec|mil.nz|mil.pl|mil.tr|mil.za|mo.cn|muni.il|nb.ca|ne.jp|ne.kr|net.au|net.br|net.cn|net.ec|net.hk|net.il|net.in|net.mm|net.mx|net.nz|net.pl|net.ru|net.sg|net.th|net.tr|net.tw|net.za|nf.ca|ngo.za|nm.cn|nm.kr|no.com|nom.br|nom.pl|nom.ro|nom.za|ns.ca|nt.ca|nt.ro|ntr.br|nx.cn|odo.br|on.ca|or.ac|or.at|or.jp|or.kr|or.th|org.au|org.br|org.cn|org.ec|org.hk|org.il|org.mm|org.mx|org.nz|org.pl|org.ro|org.ru|org.sg|org.tr|org.tw|org.uk|org.za|pc.pl|pe.ca|plc.uk|ppg.br|presse.fr|priv.pl|pro.br|psc.br|psi.br|qc.ca|qc.com|qh.cn|re.kr|realestate.pl|rec.br|rec.ro|rel.pl|res.in|ru.com|sa.com|sc.cn|school.nz|school.za|se.com|se.net|sh.cn|shop.pl|sk.ca|sklep.pl|slg.br|sn.cn|sos.pl|store.ro|targi.pl|tj.cn|tm.fr|tm.mc|tm.pl|tm.ro|tm.za|tmp.br|tourism.pl|travel.pl|tur.br|turystyka.pl|tv.br|tw.cn|uk.co|uk.com|uk.net|us.com|uy.com|vet.br|web.za|web.com|www.ro|xj.cn|xz.cn|yk.ca|yn.cn|za.com';
domains=domains.split('|');
for(var i=0;i<domains.length;i++) {
if(s==domains[i]) {
s=host[host.length-3]+'.'+s;
break;
}
}
} else {
s=host.join('.');
}
// Thanks Chris
return s;
},
extractSubDomain:function(host){
host=host.replace('http:\/\/','');
host=host.replace('https:\/\/','');
re=new RegExp("([^/]+)");
host=host.match(re)[1];
return host;
}
}
From a Firefox extension popup ;
You'll need
"permissions": [
"activeTab"
]
in your manifest or possibly tabs instead of activeTab
async function getCurrentTabUrl(){
let tabs = await browser.tabs.query({active: true, currentWindow: true}) ;
return tabs[0].url ;
}
let hostUrl = await getCurrentTab();
alert(hostUrl);
This works from a firefox "popup" extension.
browser.tabs.query({active: true, windowId: browser.windows.WINDOW_ID_CURRENT})
.then(tabs => browser.tabs.get(tabs[0].id))
.then(tab => {
console.log(tab);
});
Hallo,
I have tried to implement this in JavaScript, because I need that in my project too, but all three possible solutions didn't work. I have also implemented a small site to test it, but this also didn't work.
Here is the source code of the small site:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function Fall1 () {
alert(window.top.getBrowser().selectedBrowser.contentWindow.location.href);
}
function Fall2() {
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
alert(mainWindow.getBrowser().selectedBrowser.contentWindow.location.href);
}
function Fall3() {
alert(document.getElementById("sidebar").contentWindow.location.href);
}
</script>
</head>
<body>
<form name="Probe" action="">
<input type="button" value="Fall1"
onclick="Fall1()">
<input type="button" value="Fall2"
onclick="Fall2()">
<input type="button" value="Fall3"
onclick="Fall13()">
</form>
</body>
</html>