ASP.Net HyperLink and Download directly? - asp.net

want to have a Hyperlink-Button in a gridView in which I can display a Link for a direct download of files.
So far I am okay, but when I link the file in the NavigateURL, I don't get the file via click, I must right click -> Save as!
That I don't want. Any help?

You could set up an ashx file handler. Your ashx takes the request through the querystring, loads the proper file into memory, sets the proper response headers and streams the file to the browser:
FileInfo fileInfo = new FileInfo(PATH-TO-YOUR-FILE); //You need to specify this
context.Response.ContentType = YOUR-CONTENT-TYPE; //And this
context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
context.Response.WriteFile(fileInfo.FullName);
context.Response.Flush();
context.ApplicationInstance.CompleteRequest()
This lets you have some fine-grain control over the content that is being delivered if you have any concerns about security or maybe keeping track of who has downloaded what file, etc.

This sounds like a browser issue. Possibly the browser is trying to open up some application to handle this and failing. Double-check your application associations and/or try a new browser.

I would add also "Content-Disposition" header to response:
context.Response.AppendHeader("Content-Disposition", "attachment; filename = " + filename);

Related

Let the user download a generated file in ASP.Net

I'm creating an ASP.Net web application and I want to add an export feature. That feature will generate a string (xml, to be specific) when a button is clicked.
I want to enable the user to download this string as a file.
Do I need to create a file on the server's hard drive and open a link to that file or is there a way to download the string directly (so ASP.net takes care of creating and removing the file)?
I am currently tryig to do the following:
Response.Clear();
Response.Buffer = true;
Response.ContentEncoding = Encoding.GetEncoding(1252);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=filename.txls");
//Multiple Response.Write(string) calls to add content to the file
Response.End();
Using firebug, I found out the the user receives the headers, but the file doesn't open.
The Internet Explorer is even able to show me the response text and has a button to save the file (both options are only avilable in the developer tools) and the file is correct, but nontheless, the file still doesn't open a window (nor a in-browser-preview).
When I use the Internet Explorer (which seems to have better Visual Studio debugging integration), a JavaScript error appears:
The EnableScriptGlobalization property cannot be changed during async postbacks or after the Init event.
Calls to Response.Write() seem to be a common cause of this issue. Of course, I call exactly that method multiple times.
I figured out that the JavaScript on the webpage (the script seems to be auto-generated) tries to parse the response, but of course it isn't formatted in the asp.NET internal communication format, but in my own XML format.
How can I tell the page to treat my page as a downloadable file?
string someXML=GetXMLContent();//I assume you have an implementation of this
Response.Clear();
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", "attachment; filename=filename.xml");
Response.Write(someXML);
Response.End();
Couple of things to note. It's probably better to build up your XML string early on, then write it to the response in one shot. It makes for cleaner code, because you can separate your concerns this way.
Also, I switched the content type to "text/xml", because this is not an Excel file. Also, your file extension was incorrect. XML by convention ends in .xml. I removed the content encoding because it's not necessary most of the time. If you're dealing with weird characters feel free to add it back. Also removed the buffer in the name of removing unnecessary things.
Try this, then try opening the resulting file in your text editor and verifying the content.
The problem was that the button responsible for triggering the Excel export was not a PostBackTrigger. As soon as I had changed it, everything worked like a charm.
Nontheless, I don't know hy this fixed everything. What does it change when I set the button as a PostBackTrigger

Winform browser control "attachment" button

We have a winform app that has a browser control on it. Previously these files (always very small 10kb etc.) were stored at a unc location. We would generate some html and load the html into the browser. If we wanted to make one of these small files available we would include in the HTML an anchor tag () WHen the html was displayed in the browser control so would be the link. The user could click on the link and the file save as dialog would appear.
We are now storing these files in the db as varbinary and thus there is no longer a physical location for the anchor tag to point to. I have several thoughts but would like the members of SO who are way smarter than me to chime in.
Option 1 in my mind would be to have an image button, anchor tag, something in the html to click on. I would handle the "onclick" either in javascript or as a postback. This seems doable for my level of knowledge EXCEPT I do not know how to get the byte[] to translate into the save as dialog for the user....do I render it to disk first?
The other idea I had was to have a button that is NOT in the browser control. This button would be hidden / visible if the biz rules said to show a file. Clicking on the button would then generate the byte[] which is easily turned into a file and the save as shown dialog shown in the winform app.
So any thought or all together different suggestions welcome
TIA
JB
I understand that you are in control of the ASP.NET web page shown in the windows forms web browser control so you can edit that page and build it the way you want.
if that is true, behavior in hosted web browser or in normal IE session is the same and I would suggest to create a bunch of hyper links or buttons in the asp.net web form page each one which a specific ID, like the ID of the file to download. then you can create an handler or a button_click event handler where you get the byte[] of the file by the clicked button/link associated file Id, or from query string if you initiated an handler call, and then you start streaming down to the browser the file content, the browser will do all what is required for you.
for example, just as a starting point, a bit of code taken from here: http://social.msdn.microsoft.com/Forums/en-US/silverlightnet/thread/d6a5087f-43b1-4782-95f1-d1376130d2c8
shows you a possible way to do this from a page load, the trick is that the call to GetDocument gets the proper file content for you (in this case from the query string, imagine like if we are inside an handler processing method) and returns a class DocumentInfo which contains the bytes. you do nor need this DocumentInfo, you can just have a method which returns byte[] by File Id for example...
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string queryString = this.Request.QueryString.ToString();
if (string.IsNullOrEmpty(queryString)) return;
DocumentInfo documentInfo = GetDocument(queryString);
if (!documentInfo.HasValue) return;
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("Content-Length", documentInfo.Value.Content.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=Test.doc");
Response.BinaryWrite(documentInfo.Value.Content);
Response.End();
}
}

Play streamed audio in browser (Asp.net)

I am trying to get this to work for quite some time now. I have an asp.net page in which I am trying to play a wav file. The code in the page load event is as follows:
Response.Clear()
Response.ContentType = "audio/wav"
Response.AppendHeader("Content-Disposition", "inline;filename=" + "temp.wav")
Dim filePath As String = Server.MapPath("/temp.wav")
If Not String.IsNullOrEmpty(filePath) Then
'Here I am converting the file to a byte array,as eventually I'll be creating the wav files on the fly
Dim fileBytes As Byte() = GetFileBytes(filePath)
Response.BinaryWrite(fileBytes)
Response.Flush()
End If
The problem I am having is every time I run this page, the windows media player opens up. I would like the audio to be played using some inbuilt plugin in the browser. Something like, when you click on a voice icon, how the sound pops up without opening any player.
If I have the same content in an ashx handler, would it be better?
I could not use the embed tag because, I shall not be having a physical file on the server, it would be generated on the fly using a response stream.
Any help is appreciated!
You'll have to use Flash or ActiveX, or something like that.

Generated image display vs. download

I have an MVC action that pulls an image from a database and sends it in the response via the File(byte[], string) method. When I navigate to the action in my browser, it downloads the file rather than display it in the browser.
I'm setting the file and setting the content type to "image/jpeg". Is there another header that needs to be set in order to get it to do what I want it to do?
Ok, mystery solved.
Controller.File() has an overload that takes no filename; just data and content-type. Using that overload causes the content-disposition to be set correctly. In retrospect, I guess that makes a lot of sense.
Response.ContentType
Response.ContentType = "image/jpeg";
I would use Fiddler to compare your response headers with a normal static JPG's response headers. That will tell you for sure.

JQuery BlockUI - How to unblock UI after file download?

Using ASP.Net, JQuery and BlockUI, I'm trying to unblock the UI after a download file dialog is shown.
I block the UI when export button is clicked:
<script type="text/javascript">
$(document).ready(function(){
$('#<%= BtnExport.ClientID%>').click(function(){
$.blockUI();
});
});
</script>
After this, I generate the file server side using:
private void SendFileToUser(byte[] file, string contentType, string filename)
{
Response.Clear();
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename="+filename);
Response.OutputStream.Write(file,0,file.Length);
Response.OutputStream.Flush();
Response.End();
}
After this code has executed, I would like to unblock the UI.
I have considered different options:
Poll using Ajax calls to see if the file has been generated.
Store the file in Session and redirect to same page and generate download then.
But both options seem ackward, and I think there must be a clever JavaScript way to get a handle on or wait for a file dialog.
Any suggestions?
There is no way to check this; there is no event like ondownloadready.
But there are some work-arounds
http://gruffcode.com/2010/10/28/detecting-the-file-download-dialog-in-the-browser
Don't store the file in the session, that's a huge waste of resources. Why not just post your form data to a "download" page with a "Your file should download momentarily..." message. This is how popular download sites like www.download.com do it when arrive at their download page.
This gives the user the opportunity to retry simply by refreshing, and you don't need to worry about session timeouts because all your data is in the POST header when they arrived at the page.
The method I used is to send a cookie in addition to the file attachment which you can detect via a timeout using JavaScript and then unblock the ui
Details are here http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx

Resources