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. 看下面图片,我们能够从文件选择器选择多张图片:
mutliImagesfiles

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

希望对您Web开发有帮助。

您可能感兴趣的文章:

Html 5中自定义data-*特性


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

posted on 2012-08-22 16:26  PetterLiu  阅读(11294)  评论(0编辑  收藏  举报