Solved

How to force a file to download from a specidic path in the database table

Posted on 2010-09-03
12
277 Views
Last Modified: 2012-05-10
I'm in process to write a http handler to for force download dialog box to pop up in order to download the file the following is the cotent of my code and would like to know what should I put in the code to force download the file. All the files have been uploaded in a folder in the web server and the path including the filename is stored in a table.

This code works if the document is embedded in databse table

public class DownloadHandler : IHttpHandler {
   
   public void ProcessRequest (HttpContext context) {
    string Document_ID = context.Request.QueryString["ImID"];
    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Bdata"].ConnectionString);

    connection.Open();

    SqlCommand command = new SqlCommand("Select Document_Path from DocumentStorage where Document_ID=" + Document_ID, connection);

    SqlDataReader dr = command.ExecuteReader();

    dr.Read();

    context.Response.BinaryWrite((Byte[])dr[0]);
   
    connection.Close();

    context.Response.End();
}

    public bool IsReusable {
        get {
            return false;
        }
    }
}

However I would like to handle this code into the first one

//Write the file directly to the HTTP content output stream.
            context.Response.WriteFile(FilePath);
            context.Response.End();
            if (String.IsNullOrEmpty(filePath))
            {
                context.Response.Write("File path cannot be empty.");
                context.Response.End();
                return;
            }

            // Write back file
            context.Response.ContentType = "application/octet-stream";
            context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + Path.GetFileName(filePath) + "\"");
            context.Response.Clear();
            context.Response.WriteFile(filePath);
            context.Response.End();
        }
        catch (Exception ex)
        {
            context.Response.Write("Failed to process your request.");
            context.Response.End();
        }

Please give me an idea....

Many thank



public class DownloadHandler : IHttpHandler {
    
   public void ProcessRequest (HttpContext context) {
    string Document_ID = context.Request.QueryString["ImID"];
    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Bdata"].ConnectionString);

    connection.Open();

    SqlCommand command = new SqlCommand("Select Document_Path from DocumentStorage where Document_ID=" + Document_ID, connection);

    SqlDataReader dr = command.ExecuteReader();

    dr.Read();

    context.Response.BinaryWrite((Byte[])dr[0]);
   
    connection.Close();

    context.Response.End(); 
} 

    public bool IsReusable {
        get {
            return false;
        }
    }
}

Open in new window

0
Comment
Question by:bkerson
  • 6
  • 5
12 Comments
 
LVL 6

Expert Comment

by:judgeking
Comment Utility
What about just:

Respone.Redirect(request.Path + "\" + Path.GetFileName(filePath));
0
 

Author Comment

by:bkerson
Comment Utility
The following piece of code will give the path and the filename

SqlDataReader dr = command.ExecuteReader();
dr.Read();

but I would like to force the browser to popup the Download window.

 Respone.Redirect(request.Path + "\" + Path.GetFileName(filePath)); is not gonna work

Many thanks
0
 
LVL 6

Expert Comment

by:judgeking
Comment Utility
I think this will do what you want:
Response.AppendHeader("content-disposition", "attachment; filename=" + System.IO.Path.GetFileName("TextFile1.doc"));

  Response.ContentType = "application/msword";

  Response.WriteFile(MapPath("TextFile1.doc"));

  Response.End();

Open in new window

0
 

Author Comment

by:bkerson
Comment Utility
Hi judgeking,

Thank you for your content however my goal is not just downloading a specific file. I have a grid view and all the files to be downloaded are in a list with proper document_Id. The files are located in a folder on the web server and would like to force download with download popup window.

Another comment by taking into account my question will be greatly associated.

Many thanks

0
 
LVL 6

Expert Comment

by:judgeking
Comment Utility
OK, I suggest you just put a 'click here to download' link in your grid that points to a download page.  You could either pass the DocName or the DocID or both:
protected void Page_Load(object sender, EventArgs e)

{

    string requestedFilename = Request.Params["DocName"];

    string requestedFileID = Request.Params["DocID"];



    if (requestedFileID != null && requestedFileID.Length > 0)

        requestedFilename = GetRequestedFilename(int.Parse(requestedFileID));

    else

        requestedFilename = "TextFile1.doc"; //Test code



    Response.AppendHeader("content-disposition", "attachment; filename=" + System.IO.Path.GetFileName("/mydocfolder/" + requestedFilename));

    Response.WriteFile(MapPath("/mydocfolder/" + requestedFilename));

    Response.End();

}



protected string GetRequestedFilename(int DocID)

{

    string filename;

    //Get filename from looking up DocID in DB;

    filename = "TextFile1.doc"; //Test code

    return filename;

}

Open in new window

0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:bkerson
Comment Utility
Hi Judgeking

I think the previous code is pretty close to what I want. The browser fires a message telling that Testfile.doc is not a virtual path when I replace it to a specific path I got the same error message. I just want to pass the docid then point it to a path in where the user can download the file that correspond to the docid

Many thanks
0
 

Author Comment

by:bkerson
Comment Utility
Hi Judgeking

I just want to remind that the grid view is displaying all the files and document_id in the folder. The previous code works only if TextFile1.doc exist in the folder. what about if the user is clicking on another link with a different docid that point to another file.

So the previous code works only if we have one file. What I need is to have the user download any file they want without dictating the user a specific file. Anyway you are so close to help me out.

Tnaks
0
 
LVL 6

Expert Comment

by:judgeking
Comment Utility
Sorry, I'm not sure how familiar you are with coding.  My example assumed you were already building a listview with document descriptions and IDs.  Your page will have to dymanically build links that fill in the docIDs.  You'll also need some way to determine what docID corresponds to what filename (that's where GetRequestedFilename comes in).

I can provide you samples of this code if you need, but you'll have to increase the points of this question to 500 for that.
0
 

Author Comment

by:bkerson
Comment Utility
Hi judgeking,

See the code attached to the question, you will figure out if increase this question to 500 is necessary. The only piece that is not working in my code is that SqlDataReader dr = command.ExecuteReader();
 and I believe this is a good way to determine what docid correspond to what filename.

Thanks
0
 
LVL 6

Expert Comment

by:judgeking
Comment Utility
Try this modified version of your code:
0
 
LVL 6

Accepted Solution

by:
judgeking earned 125 total points
Comment Utility

public void ProcessRequest (HttpContext context) {

  string Document_ID = context.Request.QueryString["ImID"];

  string Document_Path;



  SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Bdata"].ConnectionString);



  connection.Open();



  SqlCommand command = new SqlCommand("Select Document_Path from DocumentStorage where Document_ID=" + Document_ID, connection);



  SqlDataReader dr = command.ExecuteReader();



  dr.Read();

  Document_Path = dr[0];

  connection.Close();



  context.Response.AppendHeader("content-disposition", "attachment; filename=" + System.IO.Path.GetFileName(Document_Path));

  context.Response.WriteFile(MapPath(Document_Path));

  context.Response.End();

}

Open in new window

0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now