Question

I am using IIS/asp.net and have a requirement to have two links side by side on the same page. They both link to the same exact file, but with two different behaviors, one should view the file and the other should download the file.

<a title="Specifications" href="/filename.pdf">
   <img alt="View Icon" src="/images/viewIcon.jpg" />
</a>    
<a title="Specifications" href="/filename.pdf">
   <img alt="Download Icon" src="/images/downloadIcon.jpg" />
</a>

enter image description here

I have seen some tips here on SO about forcing one behavior or the other through MIME types, or via Content-Disposition: attachment

But is there anyway to have this arrangement where both live on the same page? I was hoping ideally to be able to add something to the link itself or to the href.

Thanks!

Was it helpful?

Solution

If you want to force it you can do it on the server side. I'm not sure if you are using webforms or mvc, but either way on the server side you can add something like this to the header:

Response.AddHeader("Content-Disposition", "attachment;filename=whatevernamehere.pdf");

That will force the browser to download as an attachment. You only need to do this for the 'download' link and leave the 'view' link alone (to view it in the browser).

Hope that helps!

OTHER TIPS

I ended up taking the advice I was given. My entire solution is below.

My first step was to create a handler in the root of the site which I called fileDownload.ashx.

<%@ WebHandler Language="C#" Class="fileDownload" %>
using System;
using System.Web;

public class fileDownload : System.Web.IHttpHandler
{
    public void ProcessRequest (HttpContext context) 
    {
        HttpResponse r = context.Response;
        string fileName = context.Request.QueryString["file"];
        r.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        r.ContentType = "application/octet-stream"; 
        r.WriteFile(context.Server.MapPath(fileName));
    }
    public bool IsReusable { get { return false;}}
}

Next to update the links...

<a title="Specifications" href="/filename.pdf">
   <img alt="View Icon" src="/images/viewIcon.jpg" />
</a>    
<a title="Specifications" href="/fileDownload.ashx?file=/filename.pdf">
   <img alt="Download Icon" src="/images/downloadIcon.jpg" />
</a>

Thats it! There is a little postback flicker which I'd prefer there not to be, but it does what I need. Thanks for the push Bald Programmer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top