问题
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--
回答1:
What does the FeedItem class look like? For what I see in the post info it should look something like:
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; }
}
Otherwise it will not be bound. You could try and change the action signature and see if this works:
[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
}
You could even try and add a HttpPostedFileBase parameter to your action:
[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);
}
And if you're really feeling wild and naughty, add HttpPostedFileBase to 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; }
}
This last code snippet is probably what you want to end up with, but the step-by-step breakdown might help you along.
This answer might help you along in de right direction as well: ASP.NET MVC passing Model *together* with files back to controller
回答2:
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!
来源:https://stackoverflow.com/questions/5357982/asp-net-mvc-how-to-create-action-method-that-accepts-and-multipart-form-data