I was using a file uploader using an httphandler file(.ashx), but its working in normal .net web appln. Now I am trying to use the same in MVC but not able to do that. Can any body help me to solve this isssue or suggest any other way.
1 Answer
Here's how you can upload files in ASP.NET MVC without resorting to a HttpHandler (*.ashx):
Let's assume you want to create a new user profile. Each profile has a name and a profile picture.
1) Declare a model. Use the HttpPostedFileBase type for the profile picture.
public class ProfileModel
{
public string Name { get; set; }
public HttpPostedFileBase ProfilePicture { get; set; }
}
2) Use this model to create a view which contains a form that can be used to create a new profile. Don't forget to specify the enctype="multipart/form-data".
<% using (Html.BeginForm("Add", "Profiles", FormMethod.Post,
new { enctype = "multipart/form-data" })) { %>
<%=Html.TextBoxFor(m => m.Name)%>
<input type="file" id="ProfilePicture" name="ProfilePicture" />
<input type="submit" value="Save" />
<% }%>
3) Declare an action method in your controller that accepts the posted form. Here you can access a stream representing the uploaded file. The following code example reads the stream into a byte array (buffer). Afterwards you can save the file to the file system, a database...etc.
[HttpPost]
public ActionResult Add(ProfileModel model)
{
if (model.ProfilePicture != null && model.ProfilePicture.InputStream != null)
{
var filename = model.ProfilePicture.FileName;
var buffer = new byte[model.ProfilePicture.InputStream.Length];
model.ProfilePicture.InputStream.Read(buffer, 0,
(int) model.ProfilePicture.InputStream.Length);
//...
}
}