从FileUpload中选择没有上传按钮后如何显示图像

时间:2015-03-27 11:26:21

标签: c# html asp.net

我希望当我通过FileUpload1选择图像时,应该显示图像而不需要任何上传按钮。我的代码如下:

  protected void btnsubmit_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string str = FileUpload1.FileName;
                FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "//Uploads//" + str);
                string menuImage = "~//Uploads//" + str.ToString();
             //   Image1.ImageUrl = menuimage.ToString();
                string encryptedpassword = Encryptdata(txtpassword.Text);
                string encryptedconfirmpassword = Encryptdata(txtconfirmpassword.Text);
                try
                {
                    Databasebase.NewEmployee(txtname.Text, menuImage.ToString(),

1 个答案:

答案 0 :(得分:0)

据我所知,你想在保存之前预览图像,所以:

html:

<div>
  <asp:FileUpload ID="fulImg" runat="server" />
  <asp:Button ID="btnUploadImg" runat="server" Text="Upload" OnClick="btnUploadImg_Click" />
  <asp:Image ID="img" runat="server" />
</div>

,这里有代码:

protected void btnUploadImg_Click(object sender, EventArgs e)
    {
        Session["Image"] = fulImg.PostedFile;
        Stream fs = fulImg.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        byte[] bytes = br.ReadBytes((Int32)fs.Length);
        string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
        img.ImageUrl = "data:image/png;base64," + base64String;
    }

最后保存图片:

HttpPostedFile postedFile = (HttpPostedFile)Session["Image"];
string imageName = Guid.NewGuid().ToString() + Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(Server.MapPath("yourPath") + imageName);

希望有所帮助