asp.net多文件上传实例讲解

所属分类: 网络编程 / ASP.NET 阅读数: 905
收藏 0 赞 0 分享

文件上传简单实现是非常容易的,但是想要更高的要求,比如通过ajax上传文件、一次上传多个文件、文件比较大等等,这里面的坑就不是很容易填(对于新手来说)。因此在这里我准备通过ajax实现多文件上传。在开始贴代码之前,要注意几点:

  1.<input type="file" />是必须要加name的,不知道为什么不加name属性,后台获取不到文件数据(有办法的大神可以在评论区提醒我),然后是multiple属性,当multiple="multiple"时,file控件是可以多选需要上传的文件的(<input type="file" multiple="multiple"  name="myFile" />)。

  2.form要设enctype为multiple/form-data,multipart/form-data表示:不对字符编码,在使用包含文件上传控件的表单时,必须使用该值。关于enctype的详细讲解可以查看https://www.jb51.net/web/165444.html

  3.重点来了,ajax的参数设置里面有大坑(很多人都没注意ajax的众多参数),contentType和processData需要设为false,contentType明明被要求为string类型,但是这里要设为false(我也不知道为什么),网上关于contentType的说明大多是"contentType:要求为String类型的参数,当发送信息至服务器时,内容编码类型默认为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合",还有个data要设为new FormData($(' ')[0]),想了解其他参数的可看这个https://www.jb51.net/article/95425.htm 。

  下面就是简单的前台代码:

<form id="uploadForm" enctype="multipart/form-data" action="/Login/uploadFile" method="post">
 <input type="file" multiple="multiple" id="PersonFile" name="MyFile" />
 <button type="button" id="submitFile" onclick="uploadFile()">提交</button>
</form>
//上传文件
 function uploadFile() {
  debugger
  $.ajax({
  url: '/Login/uploadFile',
  type: 'POST',
  cache: false,
  data: new FormData($('#uploadForm')[0]),
  processData: false, // 关键点
  contentType: false, // 关键点
  success: function (result) {
   if (result.Check) {
   alert("成功");
   }
   else {
   alert("失败");
   }
   var file = $("#PersonFile")
   file.after(file.clone().val(""));
   file.remove();
  }
  });
 }

现在轮到后台了,我这边后台是通过System.Web.HttpContext.Current.Request.Files获取文件数据集的,之后的代码我将以图片为例。

 [HttpPost]
 public ActionResult uploadFile()
 {
  Result<string> check = new Result<string>();
  try
  {
  HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
  int number = 0;
  for (int i = 0; i < files.Count; i++)
  {
   System.Text.StringBuilder fileName = new System.Text.StringBuilder();
   fileName.Append(@"D:\");
   fileName.Append(DateTime.Now.ToString("yyMMdd"));
   fileName.Append(@"\");
   if (!System.IO.Directory.Exists(fileName.ToString()))
   {
   System.IO.Directory.CreateDirectory(fileName.ToString());
   }
   fileName.Append(System.IO.Path.GetFileNameWithoutExtension(files[i].FileName));
   fileName.Append(DateTime.Now.ToString("yyMMddHHmmss"));
   fileName.Append(System.IO.Path.GetExtension(files[i].FileName));

   System.IO.Stream sm = files[i].InputStream;
   if (System.IO.File.Exists(@"D:\水印log.jpg"))
   {
   ImageHelper.ZoomAuto(sm, fileName.ToString(), 400, 300, "", @"D:\水印log.jpg");
   }
   else
   {
   ImageHelper.ZoomAuto(sm, fileName.ToString(), 400, 300, "水印LOG", "");
   }
   bool ok = System.IO.File.Exists(fileName.ToString());
   if (ok)
   {
   number++;
   }
  }
  if (number.Equals(files.Count))
  {
   check.Message = "上传成功!";
   check.Check = true;
  }
  else
  {
   check.Message = "失败!";
   check.Check = false;
  }
  return Json(check);
  }
  catch(Exception ex)
  {
  check.Message = ex.ToString();
  check.Check = false;
  return Json(check);
  }
 }

 /// <summary>
 /// 返回值
 /// </summary>
 public class Result<T>
 {
 public string Message { get; set; }
 public bool Check { get; set; }
 public IList<T> ResultList { get; set; }
 }

  其中用到了ImageHelper.ZoomAuto(),这个是吴剑大哥写的图片处理类,地址http://www.cnblogs.com/wu-jian/archive/2011/02/21/1959382.html。最后还有一个坑,就是asp.net对一次上传数据的大小是有限制的,要解除限制才能10个20个文件同时上传。如何解除限制?在web.config里面配置一下就OK了。代码如下:

<system.web>
 <authentication mode="None" />
 <compilation debug="true" targetFramework="4.5" />
 <!--<httpRuntime targetFramework="4.5" />-->
 <httpRuntime executionTimeout="500" maxRequestLength="409600" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" />
 </system.web>

把<httpRuntime >放<system.web>节点下。

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

更多精彩内容其他人还在看

asp.net 虚方法、抽象方法、接口疑问

asp.net 虚方法、抽象方法、接口疑问等说明。
收藏 0 赞 0 分享

c#  操作符?? null coalescing operator

?? "null coalescing" operator 是c#新提供的一个操作符,这个操作符提供的功能是判断左侧的操作数是否是null,如果是则返回结果是右侧的操作数;非null则返回左侧的操作数。
收藏 0 赞 0 分享

.net 反序题目的详细解答第1/2页

在各种答案,以及平时面试过程中,这道题总归会有一些非常典型的错误发生。其中给老赵的感觉也非常有意思,不知其中的“思路”是否如老赵猜测那样。
收藏 0 赞 0 分享

implicitly convert type 'int' to 'short'的原因与解决方法

implicitly convert type 'int' to 'short'的原因与解决方法
收藏 0 赞 0 分享

比较完整的 asp.net 学习流程

好多朋友想学习后台编程语言,但请注意的事,学习后台是个循序渐进的过程,不可能一下就到位,其实不只是asp.net其它的编程语言都需要下面的一些知识。
收藏 0 赞 0 分享

官网 Ext direct包中.NET版的问题

下载了官网的 Ext direct 包进行研究,发现服务器端返回结果存在一点小问题。
收藏 0 赞 0 分享

C# XML操作 代码大全(读XML,写XML,更新,删除节点,与dataset结合等)第1/2页

C#操作XML(读XML,写XML,更新,删除节点,与dataset结合等),以下就是操作XML的所有方法,相信可以满足很大一部份的使用了。
收藏 0 赞 0 分享

c# 连接字符串数据库服务器端口号 .net状态服务器端口号

正常的数据库连接字符串配置,这是在MSSQL服务器端口是1433(默认)的情况下。
收藏 0 赞 0 分享

ASP.NET 路径问题的解决方法

相对路径和绝对路径在ASP.NET中可以用~/来解决.
收藏 0 赞 0 分享

asp.net TemplateField模板中的Bind方法和Eval方法

在TemplateField模板中为了能够有限制的或者取出数据库中某列的值时,可以用Bind和Eval方法来实现。以下是Bind方法的格式,Eval的格式也是和Bind一样的。 Bind("列的名称","显示的格式文")
收藏 0 赞 0 分享
查看更多