Thursday, March 22, 2012

Download file that is stored in Sql Server database

Hi,
I have tried to implement file download option. I can download file which is stored in any folder. Code is...

string filepath = Request.Params["file"].ToString();
string filename = Path.GetFileName(filepath);
Response.Clear();
Response.ContentType = "image/gif";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.Flush();
Response.WriteFile(filepath);

This code is working fine. But now I am facing a problem. Files (not the path) are stored in database table. User can download file from the database. How can I do this? The file may be a .txt, .doc, .xls, .jpg or .gif.

Hi,|||

Hi,

first: get the data from DB

second: use the following code:

byte[] data = TheMethodToReadTheFieldFromDB();using (Stream st =new MemoryStream(data)){long dataLengthToRead = st.Length;Response.ContentType ="text/plain";//Or other you needResponse.AddHeader("Content-Disposition","attachment; filename=\"" + theFileName + "\"");while (dataLengthToRead > 0 && Response.IsClientConnected){Int32 lengthRead = st.Read(buffer, 0, blockSize);Response.OutputStream.Write(buffer, 0, lengthRead);Response.Flush();dataLengthToRead = dataLengthToRead - lengthRead;}Response.Flush();Response.Close();}Response.End();
|||

Thank your for your reply. It is working. I want to know one more thing. Can I zip a file before download? How?

Angshujit

|||

Hi,

If you wish to zip the file, you will need to load additional library to compress the file. You can search on the web to see if there is a library for your to use. Writing the compress algorithm will take you much efforts.

|||

Hi,

Thank you for your reply. I have found a library - ZipLib. Now it is working fine. But one problem is that every time in the time of download, it creates a zip file in the root folder. How can I delete this file?

Angshujit

|||

Hi angshujit,

You can use System.IO.File.Delete() method to delete the file. You need to make sure that the file has been downloaded to the client. Then you can delete the source file.

HTH. If this does not answer you question, please feel free to mark it as Not Answered and post your reply. Thanks!

|||

Hi Kevin,

Well, my "dilema" is similar. Basically instead of showing the content on the same page that made the request (let′s say on page 'A', where page 'A' has a button that says "select") I need to show my content on a new page. So far I have this:

void gv_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { String strResult ="", strExtension =""; String strDirectory, strFileName; GridView view = (GridView)sender; Guid __ID =new Guid(view.Rows[e.NewSelectedIndex].Cells[1].Text); Content c =new Content(Connection, __ID);// Byte[] btArray = c.GetFile(ref strResult,out strExtension);if (btArray !=null) { strDirectory ="ContentFiles"; strFileName = Page.Request.PhysicalApplicationPath; strFileName = strFileName + strDirectory;if (!System.IO.Directory.Exists(strFileName)) System.IO.Directory.CreateDirectory(strFileName); strFileName +="\\" +"content" + c.HumanNumber + strExtension;// System.IO.FileStream fs;if (!System.IO.File.Exists(strFileName)) fs = System.IO.File.Create(strFileName);else fs =new System.IO.FileStream(strFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);// System.IO.BinaryWriter writer =new System.IO.BinaryWriter(fs); writer.Write(btArray); writer.Flush(); writer.Close(); fs.Close(); Page.Response.Write("<script language=\"Javascript\">var win=window.open('" + strFileName +"',null,'width=510,height=255,top=250,left=250','true');</script>"); }//if (strResult.Contains("Null")) lblMessage.Text ="No file was returned. More information: " + strResult;else lblMessage.Text = strResult; }

So the file comes out of the database, into a folder and then has to be shown in a new window. It looks fine until I ran it and I get a JavaScript error saying: "Access Denied". I went on to change the permissions on the folder (mind you I am running this not on IIS but using the feature that VS2005 has) where the file gets saved, allowing "All" to read, yet nothing. Could somebody give me some pointers?

Thanks!

|||

Hi Kevin,

Well, my "dilema" is similar. Basically instead of showing the content on the same page that made the request (let′s say on page 'A', where page 'A' has a button that says "select") I need to show my content on a new page. So far I have this:

void gv_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { String strResult ="", strExtension =""; String strDirectory, strFileName; GridView view = (GridView)sender; Guid __ID =new Guid(view.Rows[e.NewSelectedIndex].Cells[1].Text); Content c =new Content(Connection, __ID);// Byte[] btArray = c.GetFile(ref strResult,out strExtension);if (btArray !=null) { strDirectory ="ContentFiles"; strFileName = Page.Request.PhysicalApplicationPath; strFileName = strFileName + strDirectory;if (!System.IO.Directory.Exists(strFileName)) System.IO.Directory.CreateDirectory(strFileName); strFileName +="\\" +"content" + c.HumanNumber + strExtension;// System.IO.FileStream fs;if (!System.IO.File.Exists(strFileName)) fs = System.IO.File.Create(strFileName);else fs =new System.IO.FileStream(strFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);// System.IO.BinaryWriter writer =new System.IO.BinaryWriter(fs); writer.Write(btArray); writer.Flush(); writer.Close(); fs.Close(); Page.Response.Write("<script language=\"Javascript\">var win=window.open('" + strFileName +"',null,'width=510,height=255,top=250,left=250','true');</script>"); }//if (strResult.Contains("Null")) lblMessage.Text ="No file was returned. More information: " + strResult;else lblMessage.Text = strResult; }

So the file comes out of the database, into a folder and then has to be shown in a new window. It looks fine until I ran it and I get a JavaScript error saying: "Access Denied". I went on to change the permissions on the folder (mind you I am running this not on IIS but using the feature that VS2005 has) where the file gets saved, allowing "All" to read, yet nothing. Could somebody give me some pointers?

Thanks!

|||

void gv_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) { String strResult ="", strExtension =""; String strDirectory, strFileName, strUrl; GridView view = (GridView)sender; Guid __ID =new Guid(view.Rows[e.NewSelectedIndex].Cells[1].Text); Content c =new Content(Connection, __ID);// Byte[] btArray = c.GetFile(ref strResult,out strExtension);if (btArray !=null) { strDirectory = Page.Request.PhysicalApplicationPath +"ContentFiles\\";if (!System.IO.Directory.Exists(strDirectory)) System.IO.Directory.CreateDirectory(strDirectory); strFileName ="content" + c.HumanNumber + strExtension;// System.IO.FileStream fs;if (!System.IO.File.Exists(strDirectory + strFileName)) fs = System.IO.File.Create(strDirectory + strFileName);else fs =new System.IO.FileStream(strDirectory + strFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);// System.IO.BinaryWriter writer =new System.IO.BinaryWriter(fs); writer.Write(btArray); writer.Flush(); writer.Close(); fs.Close(); strUrl = Page.Request.Url.ToString(); strUrl = strUrl.Remove(strUrl.LastIndexOf('/'), strUrl.Length - strUrl.LastIndexOf('/')); strUrl +="/ContentFiles/"; Page.Response.Write("<script language=\"Javascript\">" +"var win=window.open('" + strUrl + strFileName +"',null,'width=510,height=255,top=250,left=250','true');" +"</script>"); }//if (strResult.Contains("Null")) lblMessage.Text ="No file was returned. More information: " + strResult;else lblMessage.Text = strResult; }
Hi all;

I've solved the problem. To solve it I had to store the file where the page was executing (Page.Request.PhysicalApplicationPath) and then surf it by the address of the current page (Page.Request.Url.ToString()) plus the name of the file. Unfortunatelly, since my web part will go inside a Sharepoint 2007, this aproach doesn't work because I can′t surf tohttp://sharepoint/SiteDirectory/mydepartment/Content%20%20Contents/ContentFiles/contentVD00005000.pdf. The file gets stored under C:\Inetpub\wwwroot\wss\VirtualDirectories\80\ContentFiles, now the million dollar questions is, how do you get to see the file? For those who want to see the code, it is above. If anybody can help me with popup windows and Sharepoint 2007 web parts that will be awesome.

Cheers,

|||

Kevin Yu - MSFT:

Hi angshujit,

You can use System.IO.File.Delete() method to delete the file. You need to make sure that the file has been downloaded to the client. Then you can delete the source file.

Just curious,

How would you make sure the file has been dowloaded to the client?

Thanks

/Kadji

No comments:

Post a Comment