在View State中上传图像并保存文件流

时间:2013-03-29 10:32:16

标签: c# asp.net

    protected void upload_Click(object sender, EventArgs e)
{  
    if (Upload.Value !="")
    {
        System.IO.Stream fs = Upload.PostedFile.InputStream;
        img_uploadStream = Upload.PostedFile.InputStream;
        System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
        Byte[] bytes = CreateThumbnail(br.ReadBytes((Int32)fs.Length),150);
        string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
        imageField.Src = String.Format("data:{0};base64,{1}", "image/jpeg", base64String);
    }
}

上传图片后,Upload.PostedFile.InputStream已设置为空值。 我想将此输入流保存到asp.net View State以便重用。

2 个答案:

答案 0 :(得分:0)

您可以使用此代码

public Byte[] YourImage
{
get
{
if(ViewState["Key"] != null)
{
 return (Byte[]) ViewState["Key"];
}
return null;
}

set
{
  ViewState["Key"] = value;
}
}

答案 1 :(得分:0)

在upload_Click中设置ViewState:

ViewState["ImageStream"]=Upload.PostedFile.InputStream;

然后,您可以在页面中的任何位置获取您想要使用的视图状态:

System.IO.Stream fstream=(System.IO.Stream)ViewState["ImageStream"];