pdf upload functionality in telerik rich text editor - asp.net-mvc-3

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) {
...
}

Related

Google App Scripts Function to Open URL [duplicate]

Is there a way to write a google apps script so when ran, a second browser window opens to www.google.com (or another site of my choice)?
I am trying to come up with a work-around to my previous question here:
Can I add a hyperlink inside a message box of a Google Apps spreadsheet
This function opens a URL without requiring additional user interaction.
/**
* Open a URL in a new tab.
*/
function openUrl( url ){
var html = HtmlService.createHtmlOutput('<html><script>'
+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
+'if(document.createEvent){'
+' var event=document.createEvent("MouseEvents");'
+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+' event.initEvent("click",true,true); a.dispatchEvent(event);'
+'}else{ a.click() }'
+'close();'
+'</script>'
// Offer URL as clickable link in case above code fails.
+'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+'</html>')
.setWidth( 90 ).setHeight( 1 );
SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
}
This method works by creating a temporary dialog box, so it will not work in contexts where the UI service is not accessible, such as the script editor or a custom G Sheets formula.
You can build a small UI that does the job like this :
function test(){
showURL("http://www.google.com")
}
//
function showURL(href){
var app = UiApp.createApplication().setHeight(50).setWidth(200);
app.setTitle("Show URL");
var link = app.createAnchor('open ', href).setId("link");
app.add(link);
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
If you want to 'show' the URL, just change this line like this :
var link = app.createAnchor(href, href).setId("link");
EDIT : link to a demo spreadsheet in read only because too many people keep writing unwanted things on it (just make a copy to use instead).
EDIT : UiApp was deprecated by Google on 11th Dec 2014, this method could break at any time and needs updating to use HTML service instead!
EDIT :
below is an implementation using html service.
function testNew(){
showAnchor('Stackoverflow','http://stackoverflow.com/questions/tagged/google-apps-script');
}
function showAnchor(name,url) {
var html = '<html><body>'+name+'</body></html>';
var ui = HtmlService.createHtmlOutput(html)
SpreadsheetApp.getUi().showModelessDialog(ui,"demo");
}
There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.
window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)
openUrl.html
<!DOCTYPE html>
<html>
<head>
<base target="_blank">
<script>
const url1 ='https://stackoverflow.com/a/54675103';
const winRef = window.open(url1);
winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
window.onload=function(){document.getElementById('url').href = url1;}
</script>
</head>
<body>
Kindly allow pop ups</br>
Or <a id='url'>Click here </a>to continue!!!
</body>
</html>
code.gs:
function modalUrl(){
SpreadsheetApp.getUi()
.showModalDialog(
HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
'Opening StackOverflow'
)
}
Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.
It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers
Deprecated. The UI service was deprecated on December 11, 2014. To
create user interfaces, use the HTML service instead.
The example in the HTML Service linked page is pretty simple,
Code.gs
// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'Dialog title');
}
A customized version of index.html to show two hyperlinks
<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>
Building of off an earlier example, I think there is a cleaner way of doing this. Create an index.html file in your project and using Stephen's code from above, just convert it into an HTML doc.
<!DOCTYPE html>
<html>
<base target="_top">
<script>
function onSuccess(url) {
var a = document.createElement("a");
a.href = url;
a.target = "_blank";
window.close = function () {
window.setTimeout(function() {
google.script.host.close();
}, 9);
};
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
window.document.body.append(a);
}
event.initEvent("click", true, true);
a.dispatchEvent(event);
} else {
a.click();
}
close();
}
function onFailure(url) {
var div = document.getElementById('failureContent');
var link = 'Process';
div.innerHtml = "Failure to open automatically: " + link;
}
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUrl();
</script>
<body>
<div id="failureContent"></div>
</body>
<script>
google.script.host.setHeight(40);
google.script.host.setWidth(410);
</script>
</html>
Then, in your Code.gs script, you can have something like the following,
function getUrl() {
return 'http://whatever.com';
}
function openUrl() {
var html = HtmlService.createHtmlOutputFromFile("index");
html.setWidth(90).setHeight(1);
var ui = SpreadsheetApp.getUi().showModalDialog(html, "Opening ..." );
}
I liked #Stephen M. Harris's answer, and it worked for me until recently. I'm not sure why it stopped working.
What works for me now on 2021-09-01:
function openUrl( url ){
Logger.log('openUrl. url: ' + url);
const html = `<html>
<a id='url' href="${url}">Click here</a>
<script>
var winRef = window.open("${url}");
winRef ? google.script.host.close() : window.alert('Configure browser to allow popup to redirect you to ${url}') ;
</script>
</html>`;
Logger.log('openUrl. html: ' + html);
var htmlOutput = HtmlService.createHtmlOutput(html).setWidth( 250 ).setHeight( 300 );
Logger.log('openUrl. htmlOutput: ' + htmlOutput);
SpreadsheetApp.getUi().showModalDialog( htmlOutput, `openUrl function in generic.gs is now opening a URL...` ); // https://developers.google.com/apps-script/reference/base/ui#showModalDialog(Object,String) Requires authorization with this scope: https://www.googleapis.com/auth/script.container.ui See https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes
}
https://developers.google.com/apps-script/reference/base/ui#showModalDialog(Object,String) Requires authorization with this scope: https://www.googleapis.com/auth/script.container.ui See https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes

Input File with url

I have an input of file type, and i want to allow the user to select an image on his computer or just give an url, and our server gonna download the image on himself.
I have a problem because I need to use only one input to upload local images and linked images.
You can use JQuery for that,
Just keep the type of the input TextType, and on your view file
...
<button id="uploadButton">Upload Image</button>
{{ form_widget(form.image , { 'id': 'image-field' }) }}
...
<script>
..
$('#uploadButton').click(function () {
var button = $(this);
if(button.text === 'Upload Image') {
button.text('Set URL');
$('#image-field').prop('type', 'file');
} else {
button.text('Upload Image');
$('#image-field').prop('type', 'url');
}
});
..
</script>
Don't forget after submitting the form in your controller to check if the input with the name image is a file or an URL by using if ($request->files->has('imageField') ....

How can I use Ckfinder with Ckeditor?

I was used Ckeditor in my project. It was worked well. I can put picture in texts but with an url. I know that,if I want upload an picture from my pc, I must used CKfinder.
How can I use Ckfinder with Ckeditor?
I use this code to call CKeditor:
protected void Page_Load(object sender, EventArgs e)
{
String StrScript = "CKEDITOR.replace( '" + TextBox1.ClientID + "',{toolbar : 'Full'});";
ClientScript.RegisterStartupScript(this.GetType(), "Ck-Js/ckeditor", StrScript, true);
}
Thanks.
it takes nearly 5 minutes to complete setup:
Download CKEditor and CKFinder.
Put extracted code of both in one folder inside xampp as below.
Create index file (index.html) which will be containing the editor as below code.
<html>
<head>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckfinder/ckfinder.js"></script>
</head>
<body>
<h1>CKEditor CKFinder Integration using PHP</h1>
<textarea id="editor1" name="editor1" rows="10" cols="80"></textarea>
<script type="text/javascript">
var editor = CKEDITOR.replace( 'editor1', {
filebrowserBrowseUrl : 'ckfinder/ckfinder.html',
filebrowserImageBrowseUrl : 'ckfinder/ckfinder.html?type=Images',
filebrowserFlashBrowseUrl : 'ckfinder/ckfinder.html?type=Flash',
filebrowserUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
filebrowserImageUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
filebrowserFlashUploadUrl : 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash'
});
CKFinder.setupCKEditor( editor, '../' );
</script>
</body>
</html>
so your folder structure will be something like this:
htdocs
|_integrated
|_ckeditor
| |_config.js
| |_...
|_ckfinder
| |_config.php
| |_...
|_uploads
|_index.html
Now open file config.php inside ckfinder & make following changes:
function CheckAuthentication() {
return true;
}
$baseUrl = 'http://localhost/integrated/uploads/';
$enabled = true;
$config['SecureImageUploads'] = false;
$config['ChmodFolders'] = 0777 ;
Now open url http://localhost/integrated/ and try uploading image.
I think you want use CKFinder and CKEditor, try this :
Documentation : http://docs.cksource.com/CKFinder_2.x/Developers_Guide/ASP/CKEditor_Integration
http://docs.cksource.com/CKFinder_2.x/Developers_Guide/ASP/FCKeditor_Integration
En Francais : http://creer-un-site.fr/integration-du-formulaire-d-upload-ckfinder-a-l-editeur-ckeditor-202.php
If anyone is still having problems integrating CKFinder with CKEditor, try using KCFinder (http://kcfinder.sunhater.com/) instead.
It has all the same functions as CKFinder, but its free, open source, and much easier to install and setup. (Personally, I was never able to get CKFinder installed properly....)
The installation instructions for KCFinder are here:
http://kcfinder.sunhater.com/install
And the integration instructions are here:
http://kcfinder.sunhater.com/integrate
https://ckeditor.com/ckeditor-4/download/
download ckfinder place it both in single place then
<textarea class="ckeditor" id="editor1"></textarea>
place this code in footer.php or direct on page also
CKEDITOR.replace( 'editor1', {
filebrowserBrowseUrl: 'https://example.com/admin/ckfinder/ckfinder.html',
filebrowserImageBrowseUrl: 'https://example.com/admin/ckfinder/ckfinder.html?type=Images',
filebrowserUploadUrl: 'https://example.com/admin/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
filebrowserImageUploadUrl: 'https://example.com/admin/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images'
});
in ckfinder/config.php file open and make some change
$config['authentication'] = function () {
return true;
};
$config['backends'][] = array(
'name' => 'default',
'adapter' => 'local',
'baseUrl' => 'https://example.com/admin/ckfinder/userfiles/',
// 'root' => '', // Can be used to explicitly set the CKFinder user files directory.
'chmodFiles' => 0777,
'chmodFolders' => 0755,
'filesystemEncoding' => 'UTF-8',
);
That's it, it work for me.
If this is helpful for you please rate us me

How to upload file via ajax

I have file upload which doesn't use form to upload the file instead I want to upload it using ajax. I tried the following approach but I cannot pass the file. It's null. Please help. Below is my implementation.
HTML and jQuery function
<div id="Upload">
<input type="file" accept="application/x-shockwave-flash" id="virtualtourfile" enctype="multipart/form-data"/>
<input type="button" value="Upload" id="btnUpload"/>
</div>
$('#btnUpload').click(function () {
$.ajax({
url: "uploadvideo",
type:'POST',
data: $("#virtualtourfile:file"),
success: function (data) {
}
});
});
Controller
public ActionResult UploadVideo(HttpPostedFileBase file)
{
return Json("", JsonRequestBehavior.AllowGet);
}
There are a couple of options. If the client browser supports the HTML5 File API you could use it to upload a file asynchronously to the server. If you need to support legacy browsers that do not support this API you could use a file upload component such as Uploadify, Fine uploader, jquery form, ... The advantage of those plugins is that they will test the capabilities of the browser and if it supports the File API it will use it, otherwise it will fallback to older techniques such as hidden iframes or Flash movies.
I've used a few plugins and I found the Kendo UI upload plugin nice, here is a link how it works:
http://demos.kendoui.com/web/upload/async.html
and you can find the sample project for Asp.Net MVC 3 here:
http://www.kendoui.com/forums/ui/upload/upoad-with-mvc.aspx
[HttpPost]
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
// The Name of the Upload component is "attachments"
foreach (var file in attachments)
{
// Some browsers send file names with full path. This needs to be stripped.
var fileName = Path.GetFileName(file.FileName);
var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(physicalPath);
}
// Return an empty string to signify success
return Content("");
}

Validation using Html.Telerik().Upload() with MVC3

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>

Resources