0

I am making a file uploader using HTML tags. I have a column in my table Data which has a datatype varbinary(max) so files are successfully being saved in the database in binary format.

I am also displaying the list of files in a grid with an icon next to it for viewing the file. When I click on that icon it should read my data which is in binary format and then view that file.

My code for upload at code behind is:

    protected void Upload(object sender, EventArgs e)
    {           
        string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
        string contentType = FileUpload1.PostedFile.ContentType;

        using (Stream fs = FileUpload1.PostedFile.InputStream)
        {
            using (BinaryReader br = new BinaryReader(fs))
            {
                byte[] bytes = br.ReadBytes((Int32)fs.Length);
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string query = "insert into FileUploader2 values (@Name, @ContentType, @Data)";
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@Name", filename);
                        cmd.Parameters.AddWithValue("@ContentType", contentType);
                        cmd.Parameters.AddWithValue("@Data", bytes);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        Context.Response.Write("Uploaded Successfully!");                           
                    }
                }
            }
        }

        Response.Redirect(Request.Url.AbsoluteUri);
    }

I am also able to successfully read my data back. The code for which is as follows:

    [System.Web.Services.WebMethod]
    public static void ShowDocument()
    {

        string filename = string.Empty;
        string contentType = string.Empty;
        byte[] bytes = null;
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            con.Open();

            using (SqlCommand com = new SqlCommand("SELECT * FROM FileUploader2", con))
            {
                using (SqlDataReader reader = com.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        filename = (string)reader["Name"];
                        contentType = (string)reader["ContentType"];
                        bytes = (byte[])reader["Data"];
                    }
                }
            }
        }

        System.Web.HttpContext.Current.Response.ContentType = contentType;
        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; 
        filename=" + filename);
        System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);
        System.Web.HttpContext.Current.Response.Flush();
}

Now after reading, it should also display the contents of the file or a link to download the file since I'm using the attachment. But it does nothing. It is giving me the correct values after debugging. But why it is not displaying the file? What am I doing wrong? As far as I know, since I am using content-disposition, it should display on its own.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Unknown
  • 145
  • 2
  • 11

1 Answers1

0

I think you're missing the part...

    string strFileName = "FileName";//Here you have to set the File Name...

    if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "pdf")
    {
        Response.ContentType = "application/PDF";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "doc")
    {
        Response.ContentType = "application/msword";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "docx")
    {
        Response.ContentType = "application/msword";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "xls")
    {
        Response.ContentType = "application/vnd.ms-excel";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "xlsx")
    {
        Response.ContentType = "application/vnd.ms-excel";
    }
    else if (strFileName.Substring(strFileName.LastIndexOf('.') + 1).ToLower() == "ppt")
    {
        Response.ContentType = "application/vnd.ms-powerpoint";
    }
    else if (strFileName.Substring(strFileName.IndexOf('.') + 1).ToLower() == "txt")
    {
        Response.ContentType = "text/plain";
    }
    else
    {
        Response.ContentType = "text/plain";
    }

    System.IO.FileInfo file = new System.IO.FileInfo(strFileName);

    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
    Response.AddHeader("Content-Length", file.Length.ToString());

    Response.WriteFile(file.FullName);
    Response.End();

After edit, if your data is in bytes, try last time:

public void byteArrayToImage(byte[] bytes)
    {
        if (byteArray != null)
        {
            MemoryStream ms = new MemoryStream(bytes);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms, false,  false);

            img.Save(Server.MapPath("Photo/image.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);//Set Your image Location...
            ms.Close();                
        }
    }
Dale K
  • 25,246
  • 15
  • 42
  • 71
THE LIFE-TIME LEARNER
  • 1,476
  • 1
  • 8
  • 18