nopcommerce中文网

nopcommerce是国外asp.net领域一个高质量的b2c开源项目,基于EntityFramework和MVC开发,QQ群1:75272942(2000人超级群,已满) QQ群2:640322459

导航 - 搜索

asp.net mvc多文件上传

本文主要介绍asp.net mvc中使用controllerContext.HttpContext.Request.Files上传多个文件。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication2.Controllers
{
     public class HomeController : Controller
     {
         public ActionResult Index()
         {
             return View();
         }
  
         public ActionResult FileUploads()
         {
             string pathForSaving = Server.MapPath("~/Uploads");
             if (this.CreateFolderIfNeeded(pathForSaving))
             {
                 foreach (string file in Request.Files)
                 {
                     HttpPostedFileBase uploadFile = Request.Files[file] as HttpPostedFileBase;
                     if (uploadFile != null && uploadFile.ContentLength > 0)
                     {
                        var path = Path.Combine(pathForSaving, uploadFile.FileName);
                         uploadFile.SaveAs(path);
                     }
                  }
              }
              return RedirectToAction("Index");
          }
 
          // 检查是否要创建上传文件夹
          private bool CreateFolderIfNeeded(string path)
          {
              bool result = true;
              if (!Directory.Exists(path))
              {
                 try
                 {
                     Directory.CreateDirectory(path);
                 }
                 catch (Exception)
                 {
                     //TODO:处理异常
                     result = false;
                 }
           }
           return result;
       }
    }
} 
Home/Index.cshtml视图
@{
      ViewBag.Title = "Index";
      Layout = "~/Views/Shared/_Layout.cshtml";
 }
  
  @using (Html.BeginForm("FileUploads", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
  {
      


}
blog comments powered by Disqus