I'm not sure if my search terms are off but I've been looking for a way to convert binary data back to a file and then display that file using an HTML object
tag.
Basically, I want to display a PDF or some other type of file using an HTML object
. This has to be dynamically generated from binary or data type byte
instead of sourced from a location.
Normally, we can set the data
attribute to a static file location to display a PDF or other file type within the DOM but I'm trying to figure a way to somehow read a generated file on the fly, converted from binary.
What I have right now uses Response.Write
to write a file to the HTTP response header and download a file. I'm not sure where to start if I want the file to be in an HTML object
SqlConnection sqlDnldExpDocConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ExpenseReportsConnectionString"].ToString());
SqlCommand sqlDnldExpDocCmd = new SqlCommand();
sqlDnldExpDocCmd.Connection = sqlDnldExpDocConn;
sqlDnldExpDocCmd.CommandType = CommandType.Text;
sqlDnldExpDocCmd.CommandText = "SELECT [docName], [docType], [docData] FROM [ExpDocuments] WHERE [expID] = @expID";
sqlDnldExpDocCmd.Parameters.AddWithValue("@expID", Convert.ToInt32(Request.QueryString["expid"]));
sqlDnldExpDocConn.Open();
SqlDataReader sqlDnldExpDocDataReader = sqlDnldExpDocCmd.ExecuteReader(CommandBehavior.CloseConnection);
// If rows exists then there is data to display
if (sqlDnldExpDocDataReader.HasRows)
{
while (sqlDnldExpDocDataReader.Read())
{
// Read data and generate objects
string docName = sqlDnldExpDocDataReader["docName"].ToString();
string docType = sqlDnldExpDocDataReader["docType"].ToString();
Byte[] docData = (Byte[])sqlDnldExpDocDataReader["docData"];
// Prepair, Convert and download file
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
// Replace any spaces in the original file name to enable the response header to read the name
Response.AddHeader("content-disposition", "attachment; filename=" + docName.Replace(" ", "_"));
//Set the content type as file type
Response.ContentType = docType;
//Write the file content
this.Response.BinaryWrite(docData);
this.Response.End();
}
}
// If no rows exists, no data was found. Handle accordingly.
else
{
}
sqlDnldExpDocDataReader.Close();
sqlDnldExpDocConn.Close();
sqlDnldExpDocConn.Dispose();
I've thought about moving the file to a temp. location on the server and then displaying it but I'm shooting for something a little more robust. Any ideas?