Explanation of asp. net multi file upload example

  • 2021-08-16 23:42:56
  • OfStack

It is very easy to upload files simply, but if you want higher requirements, such as uploading files through ajax, uploading multiple files at a time, and the files are relatively large, it is not easy to fill in the pits (for novices). So here I'm going to upload multiple files through ajax. Before you start posting code, you should pay attention to several points:

1. < input type="file" / > It is necessary to add name. I don't know why I don't add name attribute. I can't get file data in the background (the great god who has a way can remind me in the comment area), and then multiple attribute. When multiple= "multiple", file control can select multiple files to upload ( < input type="file" multiple="multiple" name="myFile" / > ).

2. form To set enctype to multiple/form-data, multipart/form-data means that no characters are encoded and must be used when using forms containing file upload controls. A detailed explanation of enctype can be found at https://www.ofstack.com/web/165444. html

3. The key point is that there is a big hole in the parameter setting of ajax (many people don't pay attention to many parameters of ajax), contentType and processData need to be set to false, contentType is obviously required to be string type, but it should be set to false here (I don't know why), and most of the explanations about contentType on the Internet are "contentType: required to be parameters of String type. When sending information to the server, the content coding type defaults to" application/x-www-form-urlencoded ". This default is suitable for most applications. "There is also an data to be set to new FormData ($('') [0]). For other parameters, see this https://www.ofstack.com/article/95425. htm.

Here's the simple foreground code:


<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()"> Submit </button>
</form>

// Upload a file 
 function uploadFile() {
  debugger
  $.ajax({
  url: '/Login/uploadFile',
  type: 'POST',
  cache: false,
  data: new FormData($('#uploadForm')[0]),
  processData: false, //  Key point 
  contentType: false, //  Key point 
  success: function (result) {
   if (result.Check) {
   alert(" Success ");
   }
   else {
   alert(" Failure ");
   }
   var file = $("#PersonFile")
   file.after(file.clone().val(""));
   file.remove();
  }
  });
 }

Now it's the turn of the background. On my side, the background gets the file data set through System. Web. HttpContext. Current. Request. Files. I will take pictures as an example for the following code.


 [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:\ Watermark log.jpg"))
   {
   ImageHelper.ZoomAuto(sm, fileName.ToString(), 400, 300, "", @"D:\ Watermark log.jpg");
   }
   else
   {
   ImageHelper.ZoomAuto(sm, fileName.ToString(), 400, 300, " Watermark LOG", "");
   }
   bool ok = System.IO.File.Exists(fileName.ToString());
   if (ok)
   {
   number++;
   }
  }
  if (number.Equals(files.Count))
  {
   check.Message = " Upload successfully! ";
   check.Check = true;
  }
  else
  {
   check.Message = " Failure! ";
   check.Check = false;
  }
  return Json(check);
  }
  catch(Exception ex)
  {
  check.Message = ex.ToString();
  check.Check = false;
  return Json(check);
  }
 }


   /// <summary>
 ///  Return value 
 /// </summary>
 public class Result<T>
 {
 public string Message { get; set; }
 public bool Check { get; set; }
 public IList<T> ResultList { get; set; }
 }

ImageHelper.ZoomAuto () is used, which is a picture processing class written by Brother Jian Wu. The address is http://www.cnblogs.com/wu-jian/archive/2011/02/21/1959382. html. Finally, there is a pit, that is, asp. net has a limit on the size of data uploaded once, and only 10 20 files can be uploaded at the same time if the limit is lifted. How to lift the restrictions? In web. config, OK will be configured under 1. The code is as follows:


<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>

Put < httpRuntime > Put < system.web > Node.


Related articles: