2011-03-18 6 views
8

POST 메서드로 클라이언트가 보낸 multipart/form-data을 받아 들일 필요가있는 컨트롤러 메서드가 있습니다. 양식 데이터에는 2 개의 부분이 있습니다. 하나는 application/json로 일련 번호가 지정된 개체이고 다른 한 부분은 application/octet-stream으로 전송 된 사진 파일입니다.ASP.NET MVC.

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

내가 PostItem가 null here.However 문제없이 Request.File를 통해 파일을 얻을 수 있습니다 :이처럼 내 컨트롤러 방법이있다. 이유가 확실하지 않습니다. 어떤 아이디어

컨트롤러 코드 :

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

보기에 코드를 게시 할 수 있습니까? ASP.NET MVC 1을 사용하고 있습니까? –

+0

위 코드를 게시 해주십시오. 나는 MVC3를 사용하고있다. – openbytes

답변

6

무엇처럼 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); 

} 

그리고 당신이 정말로 야생을 느끼는 경우

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

이 마지막 코드는 당신이 결국 원하는 아마이지만, 단계별 휴식 : 나쁜, HttpPostedFileBaseFeedItem에 추가 아래로 당신을 도울 수 있습니다. ASP.NET MVC passing Model *together* with files back to controller

1

@Sergi 말하는 것처럼, 당신의 행동을 HttpPostedFileBase 파일 매개 변수를 추가하고 나는 MVC3 위해 모르지만 1과 2에 대해 당신이 가지고 :

이 답변뿐만 아니라 드 올바른 방향으로 함께 당신을 도울 수

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

는 희망이 도움이!