Wednesday 15 August 2012

c# - files do not download in correct format -


OK,

Actually I use an asp.net SQL Server database to access files Is able to upload and C # can not see any problem in the browser, but when I download them, they lose their original look. Word documents lose their Doc X extensions and they have to manually select to open as a Word document.

This is my code so far

  // method safe UploadBut_Click (object from the database to upload a file, EventArgs e) {Stream inpStream = DocumentsUploadControl.PostedFile InputStream; BinaryReader br = new binaryreader (instream); Byte [] size = br.ReadBytes ((int) inpStream.Length); Using (SqlConnection Conn = new SqlConnection ( "Data Source = Conn \\ sqlexpress; initial catalog = new listing using; Integrated Security = true")) {String sql = "insert attachment (AttachmentReferenceID, AttachmentType, file name, AttachmentDescription , FileUploadedBy, UploadDate) "+" value (@reference, @ type, @filename, @descr, @ uploaded, @ uploadeddate) "; Using (SqlCommand cmd = new SqlCommand (SQL, Connecticut)) {cmd.Parameters.AddWithValue ( "@ context", ReferenceDDL.Text.Trim ()); Cmd.Parameters.AddWithValue ("Type @", Document UploadTol.Posted FileTontest.TopString ()); Cmd.Parameters.AddWithValue ("@Filename", filename TB text. Rim ()); Cmd.Parameters.AddWithValue ("@Descr", size); Cmd.Parameters.AddWithValue ("@ UploadedB", session ["user name"]. ToString ()); Cmd.Parameters.AddWithValue ("@ UploadedDate", DateTime.DD.ThortDateString ()); Conn.Open (); Cmd.ExecuteNonQuery (); Conn.Close (); Response.Redirect ("Documents.aspx"); }}} // file protected void lnkDownload_Click (object sender, EventArgs e) used for the download as {LinkButton lnkbtn = LinkButton listener; GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow; Int fileId = Convert.ToInt32 (DocumentsGridView.DataKeys [gvrow.RowIndex] .Value.ToString ()); (SqlConnection Conn = New SqlConnection ("Data Source = Conn \\ sqlexpress; Initial List = New List; Integrated Security = True")) {String SQL = "AttachmentReferenceID, AttachmentType, File Name, AttachmentDescription, FileUploadedBy, UploadDate Select attachments where from AttachmentID = @ id "; (SQL Commands CMD = New SQL Commands (Sql, Con)) (CMD parameter.Advate value ("@ id", file id); conn.Open (); SqlDataReader dr = cmd.ExecuteReader (); if (dr. Reid ()) {Response.ContentType = dr [ "AttachmentType"]. ToString (); Response.AddHeader ( "material conflict", "attachment; filename = \" "+ dr [" filename "] + "\" "); Response.BinaryWrite ((byte []) Dr. [" AttachmentDescription "]); Response.End (); conn.Close ();}}}}    

You add extension / attachment type to the response AddHeader code like:

  Response Adhider ("Content-Disposition", "Attachment; Filename = \" "+ [[Filename"] + "." + Dr [ "Attachment Type"]  

Thanks .

No comments:

Post a Comment