I have in my project a page DownloadDocument.aspx and it’s codebhind is DownloadDocument.aspx.cs
In my DownloadDocument.aspx i have an anchor which take a dynamic link like this:
<a id="downloadLink" runat="server" style="margin:5px" href="<%# CONTENT_DIRECTORY_ROOT + document.Path %>" rel="nofollow noreferrer noopener">Download current file</a>
I want to add a httphandler to control the file name downloaded, How can i do it? Thanks in advance.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
How about using a generic handler (.ashx) for this?
You need to add loading specific information, like filename, contenttyp and the content itself. The sample should give you a good headstart.
public class GetDownload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (!string.IsNullOrEmpty(context.Request.QueryString["IDDownload"]))
{
context.Response.AddHeader("content-disposition", "attachment; filename=mydownload.zip");
context.Response.ContentType = "application/octet-stream";
byte[] rawBytes = // Insert loading file with IDDownload to byte array
context.Response.OutputStream.Write(rawBytes, 0, rawBytes.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
The generic handler is called from a URL, like this:
<a href="/GetDownload.ashx?IDDownload=1337" rel="nofollow noreferrer noopener">click here to download</a>
Method 2
it depends on type of file you are trying to download…because every request is gone through HTTPHandler‘s ProcessRequest. and it’s checks each and every request one by one..
You need to add any HTTPHandler to your project and need to add something like this in your web.config.
<httpHandlers> <add path="*.jpg,*.jpeg,*.bmp,*.tif,*.tiff" verb="*" type="NameofYourHandler" /> </httpHandlers>
This will check your request for every Image type.. mentioned in path attribute
Edit :
<add verb="*" path="*DownloadDocument.aspx " type="NameofYourHandler"/>
Method 3
You can try with this code
<httpHandlers> <add verb="POST" path="*.jpg,*.jpeg,*.bmp,*.tif,*.tiff" type="YourHandler" /> </httpHandlers>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0