Solved

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

Posted on 2010-09-03
12
300 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
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
U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

 

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 125 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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

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

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

832 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