Basic Image Uploader for CKEditor in WebPages in ASP.NET - razor

I am using CKEditor in a web application in ASP.NET WebPages (Razor).
I spent a number of days trying to figure out how to make and integrate a basic file manager to support uploading images to CKEditor. The documentation in this area is next to useless. Nothing addressed the WebPages environment. Lots of PHP and WebForms and MVC, but nothing specifically for WebPages.
I finally figured out how to do it and am sharing it here.
CK Editor has an attribute that can be added to the .Replace which tells CKEditor to add an "Upload" tab (that had a built-in file browser) to the Image Properties panel:
CKEDITOR.replace('editor1'
, {
filebrowserImageUploadUrl: 'imageUpload2'
}
);
where "imageUpload2" was the name of the cshtml file (imageUpload2.cshtml) that contained the upload logic. Adding that filebrowserImageUploadUrl caused the CKEditor image properties panel to be modified to display (in the newly added "Upload" menu tab) a "Browse" button and a "Send to Server" button.
The "Browse" button activates CKEditor's Built-in file browser patterned after the html input filetype "file"; the "Send To Server" button executes the file manager you coded (see below).
The procedure would be for the user to:
click on the Insert Image icon in the CKEditor menu
Click on the "Upload" tab in the image properties dialog
Click on the "Browse" button to browse folders on the client machine and select ("Open") the desired image file
Click on the "Send to Server" button to execute the file manager's code (imageUpload2.cshtml), saving the image file to the folder specified in the cshtml file and passing the url of the file back to CKEditor.
The code in the file manager is minimal - no bells or whistles:
#{
Layout = null;
var context=HttpContext.Current;
HttpPostedFile uploads = context.Request.Files["upload"];
//get full filename
string file = System.IO.Path.GetFileName(uploads.FileName);
//get extension (including the period)
string ext = System.IO.Path.GetExtension(uploads.FileName);
//CKEditorFuncNum is passed in from the image propoerties panel in CKEditor
string CKEditorFuncNum = context.Request["CKEditorFuncNum"];
//use whatever folder name you prefer - make sure it has read/write permissions on the server
string url = Href("~/imageUploads/" + file);
var message = " .jpg .jpeg .gif .png ".Contains(ext.ToLower())?"":ext+" is invalid file type";
//Save file if it is one of the allowable extensions
if(String.IsNullOrEmpty(message))
{
uploads.SaveAs(context.Server.MapPath(".") + url );
}
//create return javascript to CKEditor (must have <script></script> tags)
var responseFormat = "<script>window.parent.CKEDITOR.tools.callFunction({0}, \"{1}\", \"{2}\");</script>";
var responseText = String.Format(responseFormat, CKEditorFuncNum, url, message);
//send script back to CKEditor image properties popup and close this page
context.Response.Write(responseText);
context.Response.End();
}
I hope this saves someone else the time I wasted trying to figure out what worked.

Related

Selenium- Read a pdf that opens in New tab without url

In our application , we have a scenario where we click on a link and after clicking a new tab opens with a dynamically generated PDF.
The generated PDF opens in new tab with "about:blank" as the URL.
To verify the content of the PDF i am not able to use below code since there is no specific URL
URL TestURL = new URL("url");
BufferedInputStream TestFile = new BufferedInputStream(TestURL.openStream());
PDFParser TestPDF = new PDFParser(TestFile);
TestPDF.parse();
String TestText = new PDFTextStripper().getText(TestPDF.getPDDocument());
I don't have option to download the generated PDF as well.
Is there any way we can solve this ??
Thank you in advance.
Try using Actions class to select all the content using "CTRL+A" then copy ("CTRL+C") and then paste it somewhere you can extract the text and verify.

vb.net how to add and load an html file from resource into webbrowser control

I have a webbrowser control on form2, and the things I'd like to do are:
How can I add an HTML file into resource ?
How can I load it from resource to webbrowser control when an if-condition is true, and make it visible in the webbrowser?
For example:
If dttest.Rows(0).Item(0).ToString = TextBox1.Text Then
webbrowser.navigate(resources and the html name page)
End If
I've already tried the webbrowser.navigate but I want to load the HTML page.
This work's for me and is tried and tested... I left the If condition out as it's not pertinent of what you are trying to accomplish. Also no need to call Navigate as when you set the Uri it should load the document.
Dim filename As String = "test.html"
With Me.WebBrowser1 'Change name to reflect your name
.ScriptErrorsSuppressed = True 'I was getting script errors from site
.Url = New Uri(String.Format("file:///{0}{1}{2}/", System.IO.Directory.GetCurrentDirectory(), "/Resources/", filename))
End With
Note
If the Copy to Output Directory is not set to Copy Always for your html file (file's) you need to make that change. You can right click on the html file and select properties. Change that property as needed.

How to display word file in popup windows using mvc 4 razor

I want make display word file in pop window using mvc 4 razor. the file has been taken from specific path and the file already stored in my project.
If you need a popup with smaller size than the full-screen window, you could try with some javascript:
fileDownloadLink variable is your download link, pointing to the Action method in your controller
The second and third arguments are explained in MDN reference for window.open function here MDN: Window.open
window.open(fileDownloadLink, 'insertPopupNameHere', 'width=400,height=400')
Otherwise you can just use an anchor tag with atribute target="_blank" (this will just open new tab in most browsers).
Preview File
The code for your action method:
//Insert your mime type here, if you know it
var fileType = "application/octet-stream";
if (inline)
{
var showInlineHeader = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = result.FileName,
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = inline,
};
Response.AppendHeader("Content-Disposition", showInlineHeader.ToString());
return File(result.Content, fileType);
}
I have added to my method the if statement in order to directly download files that I don't want to be previewed.
Original answer for forcing preview if availabale, taken from Returning a file to View/Download in MVC

Direct download image from link

i am wondering if there is a way to make a direct download link for image ?
When i do something like this:
It opens the image in the browser or in new tab. I want when user click on that link to download the image instantly. Is there a way to do this with HTML/CSS or with ASP.NET MVC 3 ?
My page is something like tumblr blog with several images on the main page and "Download HQ" button next to each.
Add HTTP Header:
Content-Disposition: attachment; filename=<file name.ext>
Where is the filename you want to appear in SaveAs dialog (like finances.xls or mortgage.pdf) - without < and > symbols.
Heres an example of this in MVC framework:
public ActionResult Download()
{
var document = ...
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = document.FileName,
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(document.Data, document.ContentType);
}
You will need server side scripting to make the link downloadable, you need to set the header to
Content-Disposition:attachment;filename=some.jpg
And then read the content of the image and flush it to response object.
here is an example for asp.net
Example

Create dynamic html file from code behind and open in a new window

I'm letting my users write their own HTML from my webpage.
When they click the preview button, my code behind needs access to controls on the page (and so I understand I can't use a web method here).
It builds the HTML and saves it as a file on the server.
My question is:
Once the file has been made, I want to automatically open the file in a new window for the user to see their handy work.
I'm using vb.net, but happy to receive c# answers.
Thanks folks !
.
.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=--=-=-=--=-=-
Thank you very much Jan !!
I still have a slight problem though...
My code goes like this:
If fileExists Then
Do Until fileExists = False
tmpFormPreviewFileName = "Test" & GetRandomNumber() & ".html"
tmpFormPreviewFilePath = Server.MapPath("~") & "Pages\FormPreviews\" & tmpFormPreviewFileName
fileExists = My.Computer.FileSystem.FileExists(tmpFormPreviewFileName)
Loop
End If
My.Computer.FileSystem.WriteAllText(tmpFormPreviewFilePath, strHTML, False)
'Now open the file in a new window
btnPreview.OnClientClick = String.Format("window.open('/Pages/FormPreviews/{0}', 'myPopup', 'width=400,height=500')", tmpFormPreviewFileName)
So, the problem is - I don't know what the filename will be until after the user has clicked the preview button and the OnClientClick event won't fire until the user clicks the button for the 2nd time (which of course creates another HTML file)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=--=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-
I'm still having problems getting the popup to work.
Here's my code at the moment:
'create a JavaScript command for opening the file in popup window
Dim strScript As String = String.Format("window.open('/Pages/FormPreviews/{0}, 'myPopup', 'width=400,height=500')", tmpFormPreviewFileName)
'register the JavaScript to be executed when web page loads
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "openPopup", strScript, True)
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "ShowMsg", "javascript:alert('Test Msg');", True)
My "ShowMsg" fires succesfully, but the line above it (the popup code) doesn't seem to work. Can you see what's going wrong at all ?
1) First you have to make the saved HTML files accessible through the web.
The simplest way is to save them to some subfolder of your website - e.g. let's create a "/GeneratedPages" folder.
When saving a file to this folder, you will need to construct a physical path to this folder. You can use the Server.MapPath method for it.
You will probably also have to set access rights to allow web application wrtting data to the folder.
2) Now let's implement opening of the preview window:
Assuming your Preview button is declared in your ASXP page as follows:
<asp:Button ID="btnPreview" runat="server" Text="Preview" />
Then you have just to add the following statement to code-behind, e.g. to the Page_Load method:
// sample name of one generate file
string pageName = "page1.html";
btnPreview.OnClientClick = string.Format("window.open('/GeneratedPages/{0}', 'myPopup', 'width=400,height=500')", pageName);
More information about the used window.open method can be found in Javascript reference, e.g. here.
UPDATE:
If are constructing the file just after clicking on the button (in a postback), then you can use a RegisterStartupScript method. Your server-side click handler for the preview button can be following:
protected void btnPreview_Click(object sender, EventArgs e)
{
string tmpFormPreviewFileName;
// construct the filename and save the file
// ...
// create a JavaScript command for opening the file in popup window
string script = string.Format("window.open('/Pages/FormPreviews/{0}, 'myPopup', 'width=400,height=500')", tmpFormPreviewFileName);
// registger the JavaScript to be executed when web page loads
ClientScript.RegisterStartupScript(GetType(), "openPupup", script, true);
}
I think your missing a quote in your JavaScript (see below)
Dim strScript As String = String.Format("window.open('/Pages/FormPreviews/{0}<-- here
Try this:
Dim strScript As String = String.Format("window.open('/Pages/FormPreviews/{0}', 'myPopup', 'width=400,height=500')", tmpFormPreviewFileName)