ASP.NET MVC实现批量文件上传

2019-05-25 10:24:40于丽

[HttpPost]    
public ActionResult Upload(FormCollection form)    
{      
  foreach (string item in Request.Files)
  {        
    HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;        
    if (file==null || file.ContentLength == 0)
      continue;  
    //判断Upload文件夹是否存在,不存在就创建
    string path = Server.MapPath("..//Upload"); 
    if (!System.IO.Directory.Exists(path)) 
    {          
      System.IO.Directory.CreateDirectory(path); 
    }       
    path = AppDomain.CurrentDomain.BaseDirectory + "Upload/";       
    //获取上传的文件名  
    string fileName = file.FileName; 
    //上传   
    file.SaveAs(Path.Combine(path,fileName)); 
  }      
  return Content("<script>alert('上传文件成功');window.history.back();</script>");   
}

注意在Request.Files中,不同文件的index是上传控件的name属性值,因此在aspx页面代码中必须保证多个上传控件的name属性值互不相同。

以上便实现了批量文件上传。

本人才疏学浅,仅供大家参考,若有不当之处,请大家批评指正!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。