ASP. NET MVC realizes batch file upload

  • 2021-10-27 07:04:34
  • OfStack

According to the needs of the project, this paper studies how to upload batch files under ASP. NETMVC. First of all, introduce single file uploading; Then, how to upload multiple files is introduced.

1. Single file upload

The principle of single file upload is to put the file data into request, and transfer it directly from the page to the background controller, which is similar to transferring parameters between view and controller, and directly pasting codes and comments.
Code in the Upload. aspx file:


<form enctype="multipart/form-data" method="post">
  <input type="file" id="file" />
  <input type="submit" value=" Upload " />
</form>

Code in Controller:


[HttpPost]
public ActionResult Upload(FormCollection form)
{
  if (Request.Files.Count == 0){
        //Request.Files.Count  Number of files is 0 Upload unsuccessful 
        return View();
      }
  var file = Request.Files[0];
  if (file.ContentLength == 0){
    // The file size is large (in bytes) 0 When, do 1 Some operations 
    return View();
  }
  else{
    // File size is not 0
    file = Request.Files[0]; // On the server UpLoadFile Folder must have read and write permissions 
    string target = Server.MapPath("/")+("/Mock/Learning/");// Gets the path to the destination folder 
    string filename = file.FileName;// Get the file name 
    string path = target + filename;// Get the destination address of the store 
    file.SaveAs(path);}
    return View();
}


Note here that in ASP. NET, the default size of request is 4M, so if you want to upload a larger file, you need to change Web. config.


<system.web>
    <httpRuntime maxRequestLength="40960"/> 
</system.web>

2. Bulk file upload

The idea is to dynamically add upload controls according to user requirements through js, and upload multiple files to controller through request1.
Code in the Upload. aspx file:


<form enctype="multipart/form-data" method="post">
  <div id="FileList">
    <div>
      <input type="file" id="file" name="file0"/>
    </div>
  </div>
  <p>
    <a onclick="AddFile();"> Add a file </a>
  </p>
  <p>
    <input type="submit" value=" Upload " />
  </p>
</form>

<script>
var index = 1;    
function AddFile() {      
  var ul = document.getElementById("FileList");
  var inputDiv = document.createElement("div");
  inputDiv.setAttribute("Id", "div" + index);
  var file = document.createElement("input");
  file.setAttribute("type", "file");
  file.setAttribute("id", "file" + index);
  file.setAttribute("name", "file" + index);
  var btnDel = document.createElement("input");
  btnDel.setAttribute("type", "button");
  btnDel.setAttribute("value", " Delete ");
  btnDel.setAttribute("Id", index);
  btnDel.onclick = function() {
    inputDiv.removeChild(file);
    inputDiv.removeChild(btnDel);
    ul.removeChild(inputDiv);
  }      
  inputDiv.appendChild(file);
  inputDiv.appendChild(btnDel);
  ul.appendChild(inputDiv);
  index++;
}
</script>

Code in Controller:


[HttpPost]    
public ActionResult Upload(FormCollection form)    
{      
  foreach (string item in Request.Files)
  {        
    HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;        
    if (file==null || file.ContentLength == 0)
      continue;  
    // Judge Upload Whether the folder exists or not, create if it does not exist 
    string path = Server.MapPath("..//Upload"); 
    if (!System.IO.Directory.Exists(path)) 
    {          
      System.IO.Directory.CreateDirectory(path); 
    }       
    path = AppDomain.CurrentDomain.BaseDirectory + "Upload/";       
    // Get the uploaded file name   
    string fileName = file.FileName; 
    // Upload    
    file.SaveAs(Path.Combine(path,fileName)); 
  }      
  return Content("<script>alert(' Upload File Successfully ');window.history.back();</script>");   
}

Note that in Request. Files, the index of different files is the name property value of the upload control, so it is necessary to ensure that the name property value of multiple upload controls is different from each other in the aspx page code.

Above, batch file uploading is realized.

I am only shallow, for your reference, if there is any improper place, please criticize and correct you!


Related articles: