0

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.

0

1 Answer 1

1

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);

        //...
     }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.