这是ASP.NET MVC 3 - 文件上载的后续问题.我有一个我无法更改的URL语法.我需要以"/ person/{personID}/files"的语法将文件上传到URL.目前,我正在尝试以下方面:
的index.html
<form action="/person/2/files" method="post" enctype="multipart/form-data">
<div>Please choose a file to upload.</div>
<div><input id="fileUpload" type="file" /></div>
<div><input type="submit" value="upload" /></div>
</form>
Run Code Online (Sandbox Code Playgroud)
在加载表单时动态填充personID参数值.无论如何,当我点击"上传"时,我将回复以下操作:
UploadController.cs
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID)
{
foreach (string file in Request.Files)
{
// Request.Files is empty
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
如何使用"/ person/{personID}/files"的URL语法对文件集合和参数进行POST?我知道这是一个非常具体的要求.我的项目时间已经用完了,我完全不知道为什么我使用的方法不起作用.有人能帮帮我吗?
非常感谢你.
假设您为此自定义网址定义了路由:
routes.MapRoute(
"Upload",
"person/{uniqueid}/files",
new { controller = "Upload", action = "UploadFile" }
);
Run Code Online (Sandbox Code Playgroud)
你只需要给你的文件输入一个名字:
<div><input id="fileUpload" type="file" name="file" /></div>
Run Code Online (Sandbox Code Playgroud)
另外我建议你使用动作参数而不是循环Request.Files:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID, HttpPostedFileBase file)
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
如果你想发布多个文件:
<div><input type="file" name="files" /></div>
<div><input type="file" name="files" /></div>
<div><input type="file" name="files" /></div>
...
Run Code Online (Sandbox Code Playgroud)
使用集合:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(int uniqueID, IEnumerable<HttpPostedFileBase> files)
{
return View();
}
Run Code Online (Sandbox Code Playgroud)
您可能还会发现以下博文有用.
或者甚至更好,使用视图模型:
public class MyViewModel
{
public int UniqueID { get; set; }
public IEnumerable<HttpPostedFileBase> Files { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFile(MyViewModel model)
{
return View();
}
Run Code Online (Sandbox Code Playgroud)