Click here to Skip to main content
Licence 
First Posted 13 Jun 2007
Views 23,308
Bookmarked 16 times

How to download any file

By | 13 Jun 2007 | Article
In this article I will try to explain how we could build simple web user control to handle file download of any type it could be even HTML files.

Introduction

May be some of will say this old staff and there is hundreds of such article but may be there are true but what I did found speak in general not in details how to deal with Unicode files to download from server or multi segment file name problem epically with Firefox browser which cause lot of problems.

Background

During last couple days in I got a web project for one of our departments that contain download section provided file download for public and site members but there is was a little problem that they some times upload on site files in different formats, so there is a little problem with files with such format like htm, txt for example they open directly inside browser window which bad idea to have such option on download section. Then I decide to build web user control to force open save dialog on any browser web site open with, which I would like to provide some useful info about to you.

And I will try to focus on some problems that I faced during development of this web user control too.

Using the code

I will expect that ever one can add new user control to there own web project using any Microsoft .NET IDE. after we add this control and name it FileDownload we will go to code behind page because we will not need for GUI representation for our control.

inside our control we should specify couple of system constants and member variables:

private const string filesFolder = "~/docs/";<br />//don't use hard coded it is not recommended<br />private long fileSize = 0;<br />private int fileID = 0;

I will use hard coded file for easer understand, now after that we will go into Load event to handle with query string that hold our file id which user wants to download from our web site.

<br />protected void Page_Load(object sender, EventArgs e)<br />{<br />    //check if query string set, contain our file id, and that file id integer value<br />    if(Request.QueryString.Count > 0 && Request.QueryString["fid"] != null && int.TryParse(Request.QueryString["fid"], out fileID) )<br />    {<br />        //after check we get our file information from datanase lets say following data [File Caption, File Name on server]<br />    //Clear all content output for buffer stream<br />    Response.Clear();<br />    //clear all header submitted by response<br />    Response.ClearHeader();<br />    Response.ClearContent();<br /><br />    //Add new page header to allow open save dialog<br />    //Where we set file name that appear to user downloaded file as it is caption and replaced spaces by (_) and removed any other special characters because both of them cause problems on firefox<br />    Response.AddHeader("Content-Disposition", "attachment; filename=" + FileCaption.Replace(" ","_").Trim("'!@#$%^&*()_+".ToCharArray()) + FileNameOnServerName.Substring(file.Name.LastIndexOf(".")));<br /><br />    //Map file path to load path into dialog box stream<br />    string filePath = Server.Map(
filesFolder + FileNameOnServer);<br /><br />    //Now we create stream object to get some information about file such as file size<br /><br />    System.IO.FileStream stream = null;<br />    <br />    try {<br />        stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open);<br />        
fileSize  = stream.Length;<br /><br />       Response.AddHeader("Content-Length", fileSize.ToString());<br />       Response.ContentType = "application/octet-stream";  <br />    }<br />    catch {} <br />    finally<br />    {<br />       if ( stream != null )<br />            stream.Close();<br />    }<br />    <br />    //now pass file data into response<br />    try {<br />        Response.WriteFile(filePath, 0, fileSize);<br />    }catch{System.IO.Exception){}    <br /><br />    Response.End();<br />}<br />

After we set this code now we can use this control inside any page so we can handle file download on any browser type.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Mohm'ed Melhem

Software Developer (Senior)

Palestinian Territory (Occupied) Palestinian Territory (Occupied)

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionProblem with '_' PinmemberMember 42349945:42 4 Oct '10  
AnswerRe: Problem with '_' PinmemberMember 423499422:43 6 Oct '10  
GeneralRe: Problem with '_' PinmemberMohm'ed Melhem0:41 8 Oct '10  
QuestionReading from a Database PinmemberBrian Graffius4:25 21 Sep '08  
GeneralThanks and a few changes Pinmemberred22:55 5 Sep '07  
GeneralOpen any file PinmemberGovardhana Reddy4:21 28 Jul '07  
AnswerRe: Open any file PinmemberMohm'ed18:50 28 Jul '07  
Generalthanks a lot Pinmemberambot20072:20 27 Jun '07  
GeneralRe: thanks a lot PinmemberMohm'ed19:48 28 Jun '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 14 Jun 2007
Article Copyright 2007 by Mohm'ed Melhem
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid