Introduction: In this article today I will
explain how we can preview the image before upload and save in asp.net
Description:
In the previous article I have explained Image preview after upload in asp.net, Validation for minimum and maximum price using Jquery, Show Gridview row detail in Tooltip on mousehover using Jquery in asp.net;Validate Listbox using Require filed validator control in asp.net,Create a dynamic Slider in asp.net, and Validate Dropdownlist using Require filed validator control in asp.net.
Add a
webform to project. After add the below given script and style to head section of
page:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
$("#FileUpload1").on("change", function
()
{
var files = !!this.files
? this.files : [];
if (!files.length || !window.FileReader) return;
if (/^image/.test( files[0].type)){
var reader = new
FileReader();
reader.readAsDataURL(files[0]);
reader.onloadend = function(){
$("#imagePreview").css("background-image", "url(" + this.result
+ ")");
}
}
});
});
</script>
<style>
#imagePreview {
width: 250px;
height: 250px;
background-position: center
center;
background-size: cover;
-webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, .3);
display: inline-block;
}
</style>
Design page
as shown below:
<center>
<fieldset style="width:35%">
<legend>Preview Image before upload</legend>
<table>
<tr><td>Upload Image:</td><td>
<asp:FileUpload ID="FileUpload1"
runat="server"
/><br />
<asp:Label ID="lblmessage"
runat="server"></asp:Label></td></tr>
<tr><td></td><td><table><tr><td>
<asp:Image ID="imagePreview"
runat="server"
/></td></tr></table></td></tr>
<tr><td></td><td> <asp:Button ID="btnupload" runat="server" Text="Upload Image"
onclick="btnupload_Click"
/></td></tr>
</table>
</fieldset>
</center>
Now on
button click event write the given code (C#):
protected void
btnupload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string path = Server.MapPath("~/Images/") + FileUpload1.FileName;
FileUpload1.SaveAs(path);
}
else
{
lblmessage.Text = "Select image to
Upload";
}
}
In VB:
Protected Sub
btnupload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
btnupload.Click
Dim path As String
If FileUpload1.HasFile Then
path = Server.MapPath("~/images/")
+ FileUpload1.FileName
FileUpload1.SaveAs(path)
Else
lblmessage.Text = "Select image to Upload"
End If
End Sub
Build the
project and run.
Result:
Is this article helpful for you?
not working this :(
ReplyDeletecan i know the eror/isue? code is tested and working for me....
ReplyDeletenot working , can you upload your demo here..?
ReplyDelete