inforakesha

A fine WordPress.com site

Uploading image in file in MVC

Leave a comment

STEP1 In View

 

<p>
@using(Html.BeginForm("Index","Image",FormMethod.Post,new{enctype="multipart/form-data"}))
{
<labelfor="file">UploadImage:</label>
<inputtype="file"name="file12"id="file"onclick="validate()"/>
<inputtype="submit"value="UploadImage"/>

<imgsrc=""alt="image"id="img1"width="150px"/>

}
</p>

Step 2:-

 

In controller

[HttpPost]
publicActionResultIndex(HttpPostedFileBasefile12)
{
if(CheckImageFile(file12.FileName))
{
ViewBag.Success="s";
stringpath=System.IO.Path.Combine(Server.MapPath("~/Images"),System.IO.Path.GetFileName(file12.FileName));
file12.SaveAs(path);
ViewBag.Message="Fileuploadedsuccessfully";
ViewBag.Url="/Images/"+System.IO.Path.GetFileName(file12.FileName);
}
else{
ViewBag.Message="Pleaseselectproperfileforimagelikepng,jpeg,etc";
}
returnView();

}
[HttpGet]
publicActionResultIndex()
{
returnView();
}

Step 3:-
In View writ Javascript function
<scripttype="text/javascript">
$(function(){
alert("insertingimages");
//varurl="/Images/Tulips.jpg";
//$("#image").attr("src",url);

//alert('@ViewBag.Url');

if('@ViewBag.Success'=='s'){
alert('@ViewBag.Message');
$("#img1").attr("src",'@ViewBag.Url');
}
else{
alert('@ViewBag.Message');
$("#img1").attr("src",'/Images/no_image.gif');

}

})

</script>

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s