I am working in asp.net mvc using c#.
I want to upload an image which is selected from file browser window and is included inside a form tag.
<form id="uploader" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileInput"/>
In the same view,I have other fields which is not a part of the form.I am sending those fields through ajax by converting them to JSON Object..Along with this i want to add the image also...Please help me to do this...
As question not much clear I'm showing example here what I assumed.
you can use jquery forms plugin.
Add jquery forms plugin
<script src="http://malsup.github.com/jquery.form.js"></script>
ViewPage
@using (Ajax.BeginForm("YourAction", "YourController", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
{
@Html.AntiForgeryToken()
//I assume other fields are
<input id="FirstName" name="FirstName" type="text"/>
<input id="LastName" name="LastName" type="text"/>
//Image upload
<input type="file" name="files">
<br>
<input type="submit" value="Upload File to Server">
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public void YourAction(IEnumerable<HttpPostedFileBase> files, string FirstName, string LastName)
{
if (files != null)
{
foreach (var file in files)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// TODO: need to define destination
var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
file.SaveAs(path);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With