Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC. How to create Action method that accepts and multipart/form-data

I have a Controller method that needs to accept multipart/form-data sent by the client as a POST request. The form data has 2 parts to it. One is an object serialized to application/json and the other part is a photo file sent as application/octet-stream. I have a method on my controller like this:

[AcceptVerbs(HttpVerbs.Post)]
void ActionResult Photos(PostItem post)
{
}

I can get the file via Request.File without problem here.However the PostItem is null. Not sure why? Any ideas

Controller Code:

/// <summary>
/// FeedsController
/// </summary>
public class FeedsController : FeedsBaseController
{
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Photos(FeedItem feedItem)
    {
        //Here the feedItem is always null. However Request.Files[0] gives me the file I need  
        var processor = new ActivityFeedsProcessor();
        processor.ProcessFeed(feedItem, Request.Files[0]);

        SetResponseCode(System.Net.HttpStatusCode.OK);
        return new EmptyResult();
    }

}

The client request on the wire looks like this:

{User Agent stuff}
Content-Type: multipart/form-data; boundary=8cdb3c15d07d36a

--8cdb3c15d07d36a
Content-Disposition: form-data; name="feedItem"
Content-Type: text/xml

{"UserId":1234567,"GroupId":123456,"PostType":"photos",
    "PublishTo":"store","CreatedTime":"2011-03-19 03:22:39Z"}

--8cdb3c15d07d36a
Content-Disposition: file; filename="testFile.txt"
ContentType: application/octet-stream

{bytes here. Removed for brevity}
--8cdb3c15d07d36a--
like image 571
openbytes Avatar asked Mar 18 '11 21:03

openbytes


1 Answers

As @Sergi say, add HttpPostedFileBase file parameter to your action and I don't know for MVC3 but for 1 and 2 you have to specify in the form/view that you will post multipart/form-data like this :

<% using (Html.BeginForm(MVC.Investigation.Step1(), FormMethod.Post, new { enctype = "multipart/form-data", id = "step1form" }))

And this is in my controller :

[HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "Admin, Member, Delegate")]
    public virtual ActionResult Step1(InvestigationStep1Model model, HttpPostedFileBase renterAuthorisationFile)
    {
        if (_requesterUser == null) return RedirectToAction(MVC.Session.Logout());

        if (renterAuthorisationFile != null)
        {
            var maxLength = int.Parse(_configHelper.GetValue("maxRenterAuthorisationFileSize"));
            if (renterAuthorisationFile.ContentLength == 0)
            {
                ModelState.AddModelError("RenterAuthorisationFile", Resources.AttachAuthorizationInvalid);
            }
            else if (renterAuthorisationFile.ContentLength > maxLength * 1024 * 1204)
            {
                ModelState.AddModelError("RenterAuthorisationFile", string.Format(Resources.AttachAuthorizationTooBig, maxLength));
            }
        } 
        if(ModelState.IsValid)
        {
            if (renterAuthorisationFile != null && renterAuthorisationFile.ContentLength > 0)
            {
                var folder = _configHelper.GetValue("AuthorizationPath");
                var path = Server.MapPath("~/" + folder);
                model.RenterAuthorisationFile = renterAuthorisationFile.FileName;
                renterAuthorisationFile.SaveAs(Path.Combine(path, renterAuthorisationFile.FileName));
            }
            ...
            return RedirectToAction(MVC.Investigation.Step2());
        }
        return View(model);
    }

Hope it helps!

like image 122
VinnyG Avatar answered Sep 28 '22 21:09

VinnyG