I've seen this:
How can I store a byte[] list in viewstate?
and I'm trying to do the same with byte[] from a FileUpload:
<asp:FileUpload ID="Documento" runat="server" />
<asp:ImageButton ID="BtnUpload" runat="server" OnClick="BtnUpload_Click" CausesValidation="false" />
<asp:Panel ID="DocumentoAllegato" runat="server" Visible="false">
<asp:ImageButton ID="BtnDownloadDocumento" runat="server" OnClick="BtnDownloadDocumento_Click" CausesValidation="false" />
<asp:ImageButton ID="BtnEliminaDocumento" runat="server" OnClick="BtnEliminaDocumento_Click" />
</asp:Panel>
protected void BtnUpload_Click(object sender, ImageClickEventArgs e)
{
if (Documento.HasFile)
{
ViewState["myDoc"] = Documento.FileBytes;
Documento.Visible = false;
BtnUpload.Visible = false;
DocumentoAllegato.Visible = true;
}
}
protected void BtnDownloadDocumento_Click(object sender, ImageClickEventArgs e)
{
byte[] file = null;
if (ViewState["myDoc"] != null)
{
file = (byte[])ViewState["myDoc"];
}
MemoryStream ms = new MemoryStream(file);
Response.Clear();
Response.Buffer = false;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-disposition", string.Format("attachment; filename={0};", "Allegato.pdf"));
ms.WriteTo(Response.OutputStream);
}
protected void BtnEliminaDocumento_Click(object sender, ImageClickEventArgs e)
{
ViewState["myDoc"] = null;
FuDocumento.Visible = true;
BtnUpload.Visible = true;
DocumentoAllegato.Visible = false;
}
But when I upload a file and I try to download it from the ImageButton it comes with more size and if I try to open it says it's dameged and cannot be open.. What I'm doing wrong?
UPDATE:
Tried doing:
ViewState["myDoc"] = Convert.ToBase64String(FuDocumento.FileBytes);
and
file = Convert.FromBase64String((string)ViewState["myDoc"]);
But still same problem. So I've tried to edit the PDF with Notepad++ and over the %%EOF line there's the entire asp page code!! Deleting that part and saving the PDF it turn OK, why It's doing that? That's something wrong in
ms.WriteTo(Response.OutputStream);
?
UPDATE 2:
Changed the ViewState with an hiddenfield:
<asp:HiddenField ID="myDoc" runat="server" />
myDoc.Value = Convert.ToBase64String(FuDocumento.FileBytes);
file = Convert.FromBase64String(myDoc.Value);
And adding in the download part:
Response.End();
It's now working!
The problem was I miss the Response.End() in the download part, so it was adding the entire asp page code inside the pdf file..
Good suggestions are to use Convert.ToBase64String from Gavin and HiddenField instead of ViewState from Arindam Nayak.