NomenNescio
NomenNescio

Reputation: 3030

ASP.NET download menu from a link

I'm trying to solve the following problem:

I have a download button that when clicked, redirects to a file for download. Example:

Response.Redirect("http://www.example.com/data/file1.zip");

when this button is clicked you get a menu in that you can press OK to download.

But if I have the following:

Response.Redirect("http://www.example.com/data/textfile.txt");

I get a piece of text instead. I don't want this behavior.

How can I make a menu pop all cases when you click to download the file.

I tried the following:

Response.ContentType = "application/octet-stream";

Response.Redirect("http://www.example.com/data/" + filename);

But if I click on it I still just get the contents of the txt in the browser. Is there any way to check if this mime type is actually being applied?

Upvotes: 0

Views: 600

Answers (2)

Tjassens
Tjassens

Reputation: 922

instead of doing the above just use a link tag and set the href to the url of the file. This will not require redirection or adjusting the context.

<a href="<link to file>" title="">Download me </a>

and this will prompt you to save or open...

doesnt work for txt files, does work for other files though

Upvotes: 0

kolin
kolin

Reputation: 2344

You need to set the response type,

octet-stream should force the user to open or save the file

something like

public class Download : IHttpHandler {
    public void ProcessRequest (HttpContext context) {
        string filename = context.Request.QueryString["file"];
        string file = context.Server.MapPath(filename);
        context.Response.ContentType = "application/octet-stream";
        context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename));
        try
        {
            context.Response.TransmitFile(file);
        }
        catch (Exception ex)
        {
            SendFailedDownload(filename, context);
        }
        finally
        {
        }
    }
}

Upvotes: 4

Related Questions