在您的控制器中,您可以通过以下方式访问上传的文件:
if(Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) {
HttpPostedFileBase postFile = Request.Files.Get(0);
string filename = GenerateUniqueFileName(postFile.FileName);
postFile.SaveAs(server.MapPath(FileDirectoryPath + filename));
}
protected virtual string GenerateUniqueFileName(string filename) {
// get the extension
string ext = Path.GetExtension(filename);
string newFileName = "";
// generate filename, until it's a unique filename
bool unique = false;
do {
Random r = new Random();
newFileName = Path.GetFileNameWithoutExtension(filename) + "_" + r.Next().ToString() + ext;
unique = !File.Exists(FileDirectoryPath + newFileName);
} while(!unique);
return newFileName;
}
文本字段将像往常一样到达您的控制器操作,即 Request.Form[...]。请注意,您还需要将表单上的 enctype 设置为“multipart/form-data”。听起来您对 ASP.NET MVC 了解得足够多,可以完成剩下的工作。另请注意,您可以按如下方式在 aspx 视图中声明表单标记,但如果您愿意,可以使用更传统的方法。
<% using(Html.BeginForm<FooController>(c => c.Submit(), FormMethod.Post, new { enctype = "multipart/form-data", @id = formId, @class = "submitItem" })) { %>
<% } %>