Creating File Download Links MVC3 Razor View with Model - c#

I am attempting to create links in my view so the end user can download the files in my model. In internet explorer I can right click and download from the link but I cannot left click (it does not open the file). Firefox gives me a message when I click the file that it does'nt know how to open this address, because the protocol (d) isn't associated with any program.
Here is how I am creating the link.
#{
foreach (var EpubFile in item.files)
{
if(File.Exists(System.Configuration.ConfigurationManager.AppSettings["UploadFileDirectory"] + EpubFile.FileReference))
{
string link = System.Configuration.ConfigurationManager.AppSettings["UploadFileDirectory"] + EpubFile.FileReference;
#EpubFile.OriginalFileName
}
}
}

Make sure the link is prefixed with http:// and is a full or partial path in URL form, not in filename form. E.g., c:\inetpub\wwwroot\foo\files\myfile.txt should be /files/myfile.txt. You can use Server.MapPath to obtain the relative path of a file under your web application root.

Related

Load a local HTML file in the current directory with WebVIew2 (Windows)

I'm trying to create a barebones WebView2 app that lets me load a specific HTML file from the same directory as wherever the app is located (so if it's on the desktop, installed in the C:\Windows\ directory, C:\Users\Poopy\, wherever. The HTML file will be titled main.html (Or I'll change it to index.html)
Still, how can I get whatever the current directory is, and create a file path to load when the app starts?
After some poking around, this is what my Form1.cs has:
if (webView != null && webView.CoreWebView2 != null) {
string currentPath = Directory.GetCurrentDirectory();
string text = System.IO.File.ReadAllText(currentPath + #"\main.html");
webView.CoreWebView2.NavigateToString(text);
this.webView.Source = new System.Uri(currentPath + #"\main.html");
}
What I expect to happen: The blank file, in the same folder as the app, is displayed. In the case of main.html, a white page with the text "hello world" should be displayed. I will be able to pull up the dev tools popup with F12.
What actually happens: If no source is specified in the properties, I get a blank screen with NO web page displaying. It appears no WebView form shows up; If I press F12 no dev tools pops up. If a source is specified, and it's a valid entry, I'll load the URL, or if I enter just the filename (assuming it defaults to a relative URL with just file:///main.html entered) I get a ERR_FILE_NOT_FOUND error page instead.
The SetVirtualHostNameToFolderMapping function can help with this. It lets you serve files from a folder to WebView2, and note this bit from the docs:
Relative paths are interpreted as relative to the folder where the exe of the app is in.
So something like this should do the trick:
webView.CoreWebView2.SetVirtualHostNameToFolderMapping(hostName: "mycoolapplication",
folderPath: "",
accessKind: CoreWebView2HostResourceAccessKind.Allow);
webView.CoreWebView2.Navigate("https://mycoolapplication/main.html");

Programmatically open webpage from file and click link to handle response C#

The scenario is that a mail is sent to an inbox. Attached to the mail is a html file which the user clicks to open the page in a browser. They then click a link on the webpage which opens a PDF file online.
Now, what I want to achieve programmatically with c# is to save the attached html file on disk, open the file, find the link, click it and save the file that opens to disk.
I have gotten as far as programmatically open the email and save the attached html file to disk. But now I'm sort of stuck at opening the file programmatically.
I've gotten as far as creating a FileWebRequest to open the file but I don't know how to find the link ("a" tag, only on in the whole page) and programmatically click it (in c#) so the PDF opens so I can download it and save to disk.
What needs to be done after the filewebrequest?
FileWebRequest req = (FileWebRequest)WebRequest.Create(pathToHtmlFile);
FileWebResponse res = (FileWebResponse)req.GetResponse();
// What now..?
At first you should extract the PDF URL using RegEx from html content and then download it using WebClient :
private static string FindPdfFileDownloadLink(string htmlContent)
{
return Regex.Match(htmlContent, #"^(https?:\/\/)?www\.([\da-z\.-]+)\.([a-z\.]{2,6})\/[\w \.-]+?\.pdf$").Value;
}
public static int Main(string[] args)
{
string htmlContent = File.ReadAllText("1.html");
string pdfUrl = FindPdfFileDownloadLink(htmlContent);
using (WebClient wClient = new WebClient())
{
wClient.DownloadFile(pdfUrl, #"1.pdf");
}
Console.Read();
return 0;
}
if you want to really click on link for any reason you can load the html in a hidden web browser and find the element that you want and click on it.
To load the content into WebBrowser control :
webBrowser1.Navigate(#"1.html");
and to find and click on element :
HtmlElement link = webBrowser.Document.GetElementByID("link_id_58547")
link.InvokeMember("Click")

Find the Directory of folder in root from a aspx page which is inside a folder in asp.net

I have a aspx page to upload image to a folder.The aspx page is inside a folder called admin.
If i keep the aspx page in the root directory i am able to upload file in the Image folder since both are in the root directory.
But when i do the same keeping the aspx page inside a folder,it shows Could not find a part of the path 'C:\Users\...
So how do i provide path such that i am able to upload image in a folder from a page which is also inside a folder.
Here goes my code:
if( fu_subcat.PostedFile.ContentLength>0 )
{
fn =Path.GetFileName(fu_subcat.PostedFile.FileName);
fu_subcat.SaveAs(Server.MapPath("imag/" + fn));
}
EDIT
It is mapping the path as:
Could not find a part of the path 'C:\Users\lenovo\Documents\Visual Studio 2010\WebSites\emarket\Admin\imag
But i have the folder inside emarket as emarket\imag not emarket\Admin\imag
Best to keep the image in a separate content folder, and then reference the image in a relative path, using the tilda e.g ~"content/image"
Using ~ will get you to the virtual root of your application, so Server.MapPath("~/imag/...") should do it.
This happens because when you call that code from
/Admin/page.aspx
Server.MapPath returns a path which is relative to /Admin/ - so the final path would be /Admin/imag/... To set path from the root you should add a / in front of the path.
Must be
fu_subcat.SaveAs(Server.MapPath("/imag/" + fn));
Notice / in front of the string.
Alternatively you can also add a ~ tilde
fu_subcat.SaveAs(Server.MapPath("~/imag/" + fn));
which points to a root of the current ASP.net application. This will be useful if you application is running in a virtual directory and as a part of global application.

How do you launch an html file that calls other html files in MVC?

I'm building a webpage that lists courses and allows a user to launch them.
When the user clicks the "Launch" button, it sends my HomeController the name of the folder that the course is sitting in. There's an html file in there called "launch".
My problem is that launch.html calls other html files. MVC is trying to force those files to load in the window as if they were all individual webpages, but they're partials (for example, ProductReview.html calls Login.html, Header.html, Footer.html, etc. to build one overall page).
I'm thinking that the solution to this is to make launch.html open in its own webpage, which operates independently of any models, views, or controllers. Is this possible?
Here's the code I've got right now:
public ActionResult Launch(string courseFolder)
{
return File("~/Courses/" + courseFolder + "/_Images/ProductReview.html", "text/html");
}
Any thoughts?
You don't want to return a File. You want to return a View.
But, more to the point, why don't you just build the URL you want on your landing page (with Razor or Javascript)?

Is there a way I continue on with a website while a file is being uploaded?

Background:
I am working on an undergrad research project for my CS department. The project is a website for the biology department and a key feature is that the biology students are able to upload their own .xml files and then a *model is built for them on the server side using Matlab.
The front end is in an ASP.NET, javascript and C# environment. My little association with this project is all the knowledge I have of these systems, tools and languages.
Question:
The .xml files I mentioned earlier can take hours to upload and build. My professor wants the user to be able to continue on with the page using models that are already completed while the new model is sent to the background and the user receives an email when it is completed. I've found material for sending the email, but not for continuing with the page.
I heard something about using AJAX to load a page?
Place a file upload control on your page
<asp:FileUpload ID="FileUpload1" runat="server"/>
Build an http handler to handle the file upload:
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
HttpPostedFile fileToUpload = context.Request.Files["Filedata"];
string pathToSave = HttpContext.Current.Server.MapPath("~/Files/")
+ fileToUpload.FileName;
fileToUpload.SaveAs(pathToSave);
//Process file
}
public bool IsReusable {
get {
return false;
}
}
}
Take a look if you can integrate an upload plugin like uploadify into the project(needs jQuery).
<script type = "text/javascript">
$(document).ready(function()
{
$("#<%=FileUpload1.ClientID %>").uploadify(
{
'swf': 'Scripts/uploadify.swf',
'uploader': 'Handler.ashx',
'auto': true,
'buttonText': 'Select File(s)'
});
});
</script>
If you cannot do this, you need to understand how ajax works
Ajax normally uses XMLHttpRequest, which does not allow you encode and send local files to a server.
You could, either use a Flash swf to handle the uploading on the same page, or to use a form that has a target of an invisible 1x1 iframe.
I found the code posted on this blog about file uploads in asp.net
I think having a small i-frame open up, which will actually do the upload, will let your current page continue working.
So on your current page, you ask for file location and file name and all, then open a new page in an i-frame. Let that i-frame know the source file/folder, destination file/folder, and let it work in the background. So now your current page is free to continue its work.
Hope that helps.
Use a headless Java Upload Applet.
Load the file transfer applet in an iFrame, let the user initiate the file transfer and when a user wants to browse the rest of the website, just don't reload the iFrame containing the Java Applet (which will be uploading the file). After the transfer is complete, do a JAvaScript call to close the iframe.
The following example uses a Java Applet by FileCatalyst, but the idea will be practically with any other Java FTP Applet or ActiveX
<script>
var browsePath = "";
function browseAndAdd() {
browsePath = document.FileCatalyst.browseLive(true);
}
function upload() {
document.FileCatalyst.uploadLive();
}
function clearQueue() {
document.FileCatalyst.clearQueue();
}
</script>
<!--Uses onClick for demonstration only-->
<form id="uploadform">
<!--Launch a browse dialog and add the selected file to the queue-->
<input type=button onClick="javascript:browseAndAdd();" value="Browse and Add to Queue" />
<!-- Force upload of whatever is currently found in the transfer queue -->
<input type=button onClick="javascript:upload();" value="Upload">
<!-- Clear transfer queue (can be called only if no transfers are in progress) -->
<input type=button onClick="javascript:clearQueue();" value="Clear Queue">
</form>
Apologies for lack of indentation, I find the stackoverflow markup for inserting code snipets not very user friendly.
You need to set up somekind of asynchronous processing ideally. Personally I like to use Celery and RabbitMQ for my async and messaging.

Categories

Resources