Preview image file before upload to webserver
Ref: http://blog.raminassar.com/2011/07/05/preview-image-file-before-upload-to-webserver/#.UZcVs6JHLRJ
Muddsar Khan
http://www.aspsnippets.com/Articles/Display-image-after-upload-without-page-refresh-or-postback-using-ASP.Net-AsyncFileUpload-Control.aspx
You can use javascript to preview the selected image before uploading it to the server.
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Main Page</title> <script type="text/javascript"> function FileUpload1_onchange(oFileUpload1) { document.getElementById('Image1').src = oFileUpload1.value ; } </script> </head> <body> <form id="form1" runat="server"> <asp:FileUpload ID="FileUpload1" runat="server" onchange="FileUpload1_onchange(this);"/> <asp:Image ID="Image1" runat="server" /> </form> </body> </html>
But due to security reasons, This doesn’t work on some browsers. If this doesn’t work for you, You’ll have to save the image on some temporary location in server itself and preview it. You could try something like this :
.aspx
<html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Main Page</title> <script type="text/javascript"> function FileUpload1_onchange(oFileUpload1) { document.getElementById('btnPreviewImage').click() ; } </script> </head> <body> <form id="form1" runat="server"> <asp:FileUpload ID="FileUpload1" runat="server" onchange="FileUpload1_onchange(this);" /> <asp:Button ID="btnPreviewImage" runat="server" Style="display: none;" OnClick="btnPreviewImage_Click" /> <asp:Image ID="Image1" runat="server" /> </form> </body> </html>
.aspx.cs
protected void btnPreviewImage_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string path = Server.MapPath("TempImages"); FileInfo oFileInfo = new FileInfo( FileUpload1.PostedFile.FileName); string fileName = oFileInfo.Name; string fullFileName = path + "" + fileName; string imagePath = "TempImages/" + fileName; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } FileUpload1.PostedFile.SaveAs(fullFileName); Image1.ImageUrl = imagePath; } }
Happy Programming
Rami M. Nassar
Comments
Post a Comment