MVC文件上传03-使用Request.Files上传多个文件

本篇体验在控制器方法中使用controllerContext.HttpContext.Request.Files上传多个文件。兄弟篇为:

MVC文件上传01-使用jquery异步上传并客户端验证类型和大小       
MVC文件上传02-使用HttpPostedFileBase上传多个文件     

 

□ 控制器

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.IO;
   4:  using System.Linq;
   5:  using System.Web;
   6:  using System.Web.Mvc;
   7:   
   8:  namespace MvcApplication2.Controllers
   9:  {
  10:      public class HomeController : Controller
  11:      {
  12:          public ActionResult Index()
  13:          {
  14:              return View();
  15:          }
  16:   
  17:          public ActionResult FileUploads()
  18:          {
  19:              string pathForSaving = Server.MapPath("~/Uploads");
  20:              if (this.CreateFolderIfNeeded(pathForSaving))
  21:              {
  22:                  foreach (string file in Request.Files)
  23:                  {
  24:                      HttpPostedFileBase uploadFile = Request.Files[file] as HttpPostedFileBase;
  25:                      if (uploadFile != null && uploadFile.ContentLength > 0)
  26:                      {
  27:                          var path = Path.Combine(pathForSaving, uploadFile.FileName);
  28:                          uploadFile.SaveAs(path);
  29:                      }
  30:                  }
  31:              }
  32:              return RedirectToAction("Index");
  33:          }
  34:   
  35:          // 检查是否要创建上传文件夹
  36:          private bool CreateFolderIfNeeded(string path)
  37:          {
  38:              bool result = true;
  39:              if (!Directory.Exists(path))
  40:              {
  41:                  try
  42:                  {
  43:                      Directory.CreateDirectory(path);
  44:                  }
  45:                  catch (Exception)
  46:                  {
  47:                      //TODO:处理异常
  48:                      result = false;
  49:                  }
  50:              }
  51:              return result;
  52:          }
  53:      }
  54:  }

 

□ Home/Index.cshtml视图

   1:  @{
   2:      ViewBag.Title = "Index";
   3:      Layout = "~/Views/Shared/_Layout.cshtml";
   4:  }
   5:   
   6:  @using (Html.BeginForm("FileUploads", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
   7:  {
   8:      <input type="file" name="files1" id="file1" /><br/>
   9:      <input type="file" name="files2" id="file2" /><br/>
  10:      <input type="file" name="files3" id="file3" /><br/>
  11:      <input type="submit" value="同时上传多个文件" />
  12:  }


注意:
name属性值可以不同

 

参考资料

ASP.NET MVC - 不使用HttpPostedFileBase 处理文件上传

ajaxfileupload.js可以兼容IE8以下版本实现无刷新的Form提交,上传文件。 这个版本修改了提交后台失败的几个bug 使用是需注意以下几点: 1.调用createUploadForm,此方法中增加了change参数,此参数用户给新生成的input-file元素绑定change事件,如果不需要可以不加此参数。 2.要上传的input-file元素,建议放id和name属性,而且这两个属性值要保持一致 3.后台代码中,response里的contenttype要设置为"text/html",前台的success回调中对返回值作处理 例子如下: js: $.ajaxFileUpload({ url: url, type: 'post', data: data, secureuri: false, fileElementId: fileId, // input-file的id、name属性名 dataType: 'JSON', beforeSend: function (XMLHttpRequest) { //show loading... }, success: function (data, status) { data = jQuery.parseJSON(data); success(data); }, error: function (data, status, e) { error(e); }, complete: function (XMLHttpRequest, textStatus) { //hide loading... }, change: change //需要绑定到动态生成的input-file元素上的change事件处理方法;没有的话,这个参数可以不写 }); 如果加了change,change方法中需要处理一下,因为发现会被调2次 function Upload(event) { var fileid = $(event.target).attr('id'); if(isNullOrEmpty(fileid) || /^jUploadFile\d+$/.test(fileid))return; //注意:此处过滤无效调用 //... } 后台代码(ashx): public void ProcessRequest(HttpContext context) { try { context.Response.ContentType = "text/html"; var request = context.Request; var param1 = request.Params["param1"]; //取参数 //取上传文件 if (request.Files == null || request.Files.Count <= 0) throw new ApplicationException("no file to be uploaded!"); var file = request.Files[0]; var filename = System.IO.Path.GetFileName(file.FileName); var serverpath = Path.Combine(context.Server.MapPath(ROOT), filename); file.SaveAs(serverpath); //自定义返回Json字符串 var json = '{' + string.Format(json, id, finfo.Name, extension, path) + '}'; response.Write(json); return; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值