ASP.NET MVC.Как создать метод Action, который принимает и multipart / form-data - PullRequest
8 голосов
/ 19 марта 2011

У меня есть метод Controller, который должен принимать multipart/form-data, отправленный клиентом как запрос POST. Данные формы состоят из 2 частей. Один - это объект, сериализованный в application/json, а другая часть - файл фотографии, отправленный как application/octet-stream. У меня есть метод на моем контроллере, как это:

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

Я могу получить файл через Request.File без проблем здесь. Однако PostItem имеет значение null. Не уверен почему? Любые идеи

Код контроллера:

/// <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();
    }

}

Запрос клиента на провод выглядит следующим образом:

{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--

Ответы [ 2 ]

6 голосов
/ 19 марта 2011

Как выглядит класс FeedItem? То, что я вижу в информации поста, должно выглядеть примерно так:

public class FeedItem
{
    public int UserId { get; set; }
    public int GroupId { get; set; }
    public string PublishTo { get; set; }
    public string PostType { get; set; }
    public DateTime CreatedTime { get; set; }
}

В противном случае оно не будет связано. Вы можете попробовать изменить сигнатуру действия и посмотреть, работает ли это:

[HttpPost] //AcceptVerbs(HttpVerbs.Post) is a thing of "the olden days"
public ActionResult Photos(int UserId, int GroupId, string PublishTo
    string PostType, DateTime CreatedTime)
{
    // do some work here
}

Вы даже можете попытаться добавить параметр HttpPostedFileBase к своему действию:

[HttpPost]
public ActionResult Photos(int UserId, int GroupId, string PublishTo
    string PostType, DateTime CreatedTime, HttpPostedFileBase file)
{
    // the last param eliminates the need for Request.Files[0]
    var processor = new ActivityFeedsProcessor();
    processor.ProcessFeed(feedItem, file);

}

И если вы действительно чувствуете себя диким и непослушным, добавьте HttpPostedFileBase к FeedItem:

public class FeedItem
{
    public int UserId { get; set; }
    public int GroupId { get; set; }
    public string PublishTo { get; set; }
    public string PostType { get; set; }
    public DateTime CreatedTime { get; set; }
    public HttpPostedFileBase File { get; set; }
}

Этот последний фрагмент кода, вероятно, является тем, чем вы хотите закончить, но пошаговая разбивка может помочь вам в этом.

Этот ответ также может помочь вам в правильном направлении: ASP.NET MVC передает модель * вместе * с файлами обратно в контроллер

1 голос
/ 19 марта 2011

Как говорит @Sergi, добавьте параметр файла HttpPostedFileBase к своему действию, и я не знаю, для MVC3, но для 1 и 2 вы должны указать в форме / представлении, что вы будете публиковать multipart / form-data следующим образом:1001 *

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

И это в моем контроллере:

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

Надеюсь, это поможет!

...