溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

asp.net如何實現(xiàn)多文件上傳

發(fā)布時間:2021-09-03 14:16:13 來源:億速云 閱讀:169 作者:小新 欄目:開發(fā)技術

這篇文章主要介紹asp.net如何實現(xiàn)多文件上傳,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

文件上傳簡單實現(xiàn)是非常容易的,但是想要更高的要求,比如通過ajax上傳文件、一次上傳多個文件、文件比較大等等,這里面的坑就不是很容易填(對于新手來說)。因此在這里我準備通過ajax實現(xiàn)多文件上傳。在開始貼代碼之前,要注意幾點:

  1.<input type="file" />是必須要加name的,不知道為什么不加name屬性,后臺獲取不到文件數(shù)據(jù)(有辦法的大神可以在評論區(qū)提醒我),然后是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的參數(shù)設置里面有大坑(很多人都沒注意ajax的眾多參數(shù)),contentType和processData需要設為false,contentType明明被要求為string類型,但是這里要設為false(我也不知道為什么),網(wǎng)上關于contentType的說明大多是"contentType:要求為String類型的參數(shù),當發(fā)送信息至服務器時,內(nèi)容編碼類型默認為"application/x-www-form-urlencoded"。該默認值適合大多數(shù)應用場合",還有個data要設為new FormData($(' ')[0]),想了解其他參數(shù)的可看這個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();
  }
  });
 }

現(xiàn)在輪到后臺了,我這邊后臺是通過System.Web.HttpContext.Current.Request.Files獲取文件數(shù)據(jù)集的,之后的代碼我將以圖片為例。

 [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對一次上傳數(shù)據(jù)的大小是有限制的,要解除限制才能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>節(jié)點下。

以上是“asp.net如何實現(xiàn)多文件上傳”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI