Suhaib Janjua Suhaib Janjua -4 years ago 65
ASP.NET (C#) Question

Export file by showing SaveAsDialogue in chrome

string fileName = "1001-1000-1_29_2015 2_04_22 PM.wav";
string filePath = Server.MapPath("Audio") + "\\" + fileName;


In IE, I used the following line to export my .wav file.

Response.Redirect("Audio/" + fileName);


As
Response.Redirect();
is used to redirect the user to anything (pages, files etc). So in IE it shows an
SaveAsDialogue
to the user to save it.

But in chrome, the default behavior of the browser is redirecting to the specified file and plays it in the chrome.

I want to export my .wav file by giving a
SaveAsDialogue
in both browsers.

I tried the following code for chrome:

Response.Clear();
Response.ContentType = "Audio/wav";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(filePath);
Response.Flush();
Response.End();


But still I'm not successful to transmit my .wav file in Chrome.

Answer Source

This'll sort it; by changing the mime-type of the content to a generic one:

Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(filePath);
Response.Flush();
Response.End();

Edit: Here's the exact code I'm using and it works with WAV files too:

Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename="+ fileName);
Response.WriteFile(file);
Response.End();

The save to dialogue is a client side feature that cannot be forced*. Only reason IE offers it in the first instance is because it doesn't know what to do with the file when trying to access it directly. The above method is to force it to download, not play/render directly in the browser. However you can right click the link(s) and select Save link as....

*I suppose if you were to set the mime-type up incorrectly on the server for the file type then use your original Response.Redirect method then you could but you'd be messing with the server and causing no end of headaches down the line.

If you want to change Chrome to ask you every time where to save a download to you need to to into Settings, click Show advanced settings... then scroll down to the Downloads heading where you'll see something like this:

Downloads Setting in Chrome

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download