Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

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

Posted on 2010-09-03
12
Medium Priority
?
345 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
11 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
This shares a stored procedure to retrieve permissions for a given user on the current database or across all databases on a server.
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 extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Suggested Courses

580 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