?
Solved

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

Posted on 2010-09-03
12
Medium Priority
?
335 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
12 Comments
 
LVL 6

Expert Comment

by:judgeking
ID: 33598883
What about just:

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

Author Comment

by:bkerson
ID: 33599164
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
ID: 33600629
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
Get proactive database performance tuning online

At Percona’s web store you can order full Percona Database Performance Audit in minutes. Find out the health of your database, and how to improve it. Pay online with a credit card. Improve your database performance now!

 

Author Comment

by:bkerson
ID: 33618014
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
ID: 33619633
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
 

Author Comment

by:bkerson
ID: 33646501
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
ID: 33646625
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
ID: 33647197
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
ID: 33649623
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
ID: 33655765
Try this modified version of your code:
0
 
LVL 6

Accepted Solution

by:
judgeking earned 500 total points
ID: 33655768

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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have a large data set and a SSIS package. How can I load this file in multi threading?
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Suggested Courses

764 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