In this article, we will learn how to convert a file into byte array and get back the original file from the byte array via FileUpload control.
Step 1: Create a page having control FileUpload and Button
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnGetFile" runat="server" Text="GetFile" OnClick="btnGetFile_Click"/>
</div>
Step 2: On button click, call function FileToByteArray and GetDocument
protected void btnGetFile_Click(object sender, EventArgs e)
{
string fileName = FileUpload1.PostedFile.FileName;
//To convert file into byte array
byte[] byteArray = FileToByteArray(FileUpload1.PostedFile.InputStream);
//To get back file from byte array
GetDocument(fileName, byteArray);
}
Step 3: Write FileToByteArray function to convert file into byte array
public byte[] FileToByteArray(Stream fileStream)
{
byte[] buffer = new byte[fileStream.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Step 4: Write GetDocument fumction to get back the original file from byte array
private void GetDocument(string fileName, byte[] fileContent)
{
try
{
//Split the string by character . to get file extension type
string[] stringParts = fileName.Split(new char[] { '.' });
string strType = stringParts[1];
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName.Replace(" ",""));
//Set the content type as file extension type
Response.ContentType = strType;
//Write the file content
this.Response.BinaryWrite(fileContent);
this.Response.End();
}
catch (Exception ex)
{
}
}
Hope, this will help you!
0 Comment(s)