我看到过:
如何在视图状态下存储字节[]列表?
我正在尝试对FileUpload:中的byte[]执行同样的操作
<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;
}
但是,当我上传一个文件并尝试从ImageButton下载时,它的大小更大,如果我尝试打开它,它会说它已损坏,无法打开。。我做错了什么?
更新:
尝试做:
ViewState["myDoc"] = Convert.ToBase64String(FuDocumento.FileBytes);
和
file = Convert.FromBase64String((string)ViewState["myDoc"]);
但仍然存在同样的问题。所以我试着用Notepad++编辑PDF,在%%EOF行上有整个asp页面代码!!删除那个部分并保存PDF,它就可以了,为什么要这么做?出了问题
ms.WriteTo(Response.OutputStream);
更新2:
使用隐藏字段更改ViewState:
<asp:HiddenField ID="myDoc" runat="server" />
myDoc.Value = Convert.ToBase64String(FuDocumento.FileBytes);
file = Convert.FromBase64String(myDoc.Value);
并在下载部分添加:
Response.End();
它现在工作了!
问题是我错过了下载部分的Response.End(),所以它在pdf文件中添加了整个asp页面代码
好的建议是使用Gavin和HiddenField的Convert.ToBase64String,而不是Arindam Nayak的ViewState。