用Html5与Asp.net MVC上传多个文件的包茎有院网

2012 年 11 月 14 日6060

Html 5 的有一些File API,对Form表单增强的特性,让我们轻松支持多文件上传,看下面的Html片断院网

院网如下:
<form action="/Home/Upload" enctype="multipart/form-data" id="form2" method="post">
<input type="file" name="fileToUpload" id="fileToUpload2" multiple="multiple" />
<input type="submit" value="submit" />
</form>

那在Asp.net MVC web application中,我们可以这么包茎有
院网如下:
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "form2" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="fileToUpload" id="fileToUpload2" multiple="multiple" />
<input type="submit" value="Upload Image by submit" />
}

假设这是一个HomeController下View, 即将提交到Upload的Action,看下面服务端的院网:
院网如下:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase[] fileToUpload)
{
foreach (HttpPostedFileBase file in fileToUpload)
{
string path = System.IO.Path.Combine(Server.MapPath("~/App_Data"), System.IO.Path.GetFileName(file.FileName));
file.SaveAs(path);
}

ViewBag.Message = "File(s) uploaded successfully";
return RedirectToAction("Index");
}

好的,就这么简单。 这里我们把接收到文件存储到App_Data文件夹中,然后返回Index的Action. 看下面图片,我们能够从文件选择器选择多张图片:

关于HTML5这个特性在那些浏览器支持,您可以去这里查看。 您还可以查看W3C官方的文档。我们在FireFox 14.01下测试能过。

希望对您Web开发有帮助。

0 0