mvc file control no refresh asynchronous upload operation source code

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

Preface

Uploading files should be a very common and essential operation, and there are many uploading controls provided on the Internet. Today, I encountered a problem: the input control file cannot upload asynchronously without refresh. Really feel awkward. So I tried this to deal with it for 1 time. It is mainly divided into three parts: encapsulation of upload class, html input control file processing and background controller calling.

Upload encapsulation class:

There are two main functions in this class, one is simple filtering and file renaming operation.

Filtering files includes:

File type, file size

Rename:

Where the default is no renaming, where the default is the time string DateTime. Now. ToString ("yyyyMMddHHmmss")

File address:

Can be customized. Relative address and absolute address can be used.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Web;
namespace CommonHelper
{
 public class UploadFile : System.Web.UI.Page
 {
  public UploadFile()
  {

  }
  // Error message 
  public string msg { get; set; }
  public string FullName { get; set; }
  // File name 
  public string FileName { get; set; }
  /// <summary>
  ///  File upload 
  /// by wyl 20161019
  /// </summary>
  /// <param name="filepath"> File upload address </param>
  /// <param name="size"> Specified file size </param>
  /// <param name="filetype"> File type </param>
  /// <param name="files">file Uploaded files </param>
  /// <param name="isrename"> Do you have duplicate names </param>
  /// <returns></returns>
  public bool upload_file(string filepath, int size, string[] filetype, bool isrename = false)
  {
   filepath = Server.MapPath(filepath);
   // Create if the folder does not exist 
   if (!Directory.Exists(filepath))
    Directory.CreateDirectory(filepath);
   if (HttpContext.Current.Request.Files.Count == 0)
   {
    msg = " File upload failed ";
    return false;
   }
   msg = " Upload succeeded ";
   var file = HttpContext.Current.Request.Files[0];
   if (file.ContentLength == 0)
   {
    msg = " The file size is 0";
    return false;
   }
   if (file.ContentLength > size * 1024)
   {
    msg = " File exceeds specified size ";
    return false;
   }
   var filex = HttpContext.Current.Request.Files[0];
   string fileExt = Path.GetExtension(filex.FileName).ToLower();
   if (filetype.Count(a => a == fileExt) < 1)
   {
    msg = " File type not supported ";
    return false;
   }
   if (isrename)
    FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;
   FileName = filex.FileName;
   FullName = Path.Combine(filepath, FileName);
   file.SaveAs(FullName);
   return true;
  }
 }
}

The method of uploading files is not introduced here. Look at the code comments should be easy to understand.

Page html


<div class="content">
<form method="post" target="hidden_frame" enctype="multipart/form-data" action="/CustomFrom/FormDesign/FileUpload" name="form">
<input class="m input" name="fileName" type="file">
<input class="btn file-input" value=" Submit ..." name="F2" type="submit">
<iframe id="hidden_frame" name="F2" style="display: none">
<html>
<head></head>
<body></body>
</html>
</iframe>
</form>
</div>

Note: Because the mvc upload file input control file does not support asynchronous non-refresh upload, the upload non-refresh operation is carried out by calling jump to iframe.

The above page is the html definition of the upload control. There are a few points to pay attention to

1. enctype= "multipart/form-data" must be added. enctype= "multipart/form-data" in the form means to set the MIME encoding of the form. By default, this encoding format is application/x-www-form-urlencoded and cannot be used for file uploads; Only when multipart/form-data is used can the file data be transferred completely, and the following operations are performed. enctype= "multipart/form-data" is to upload binary data; The value of input in form is passed in binary.

2. name of form should be added

3. The submit button is submit, but if you want to write js, set it to button. There's nothing to say about this.

4. style= "display: none" in iframe

That's the whole layout and submit the upload file to the background, and jump to ifrom, and then accept the method that calls the upload file above. Then in the iframe page prompt upload results, and then close iframe can be.

Background code:


 [HttpPost]
  public ActionResult FileUpload()
  {
   // Get the supported upload file format from the configuration file 
   string[] fileType = ConfigurationManager.AppSettings["fileType"].Split('|');
   // Upload file path 
   string strPath = ConfigurationManager.AppSettings["strPath"];
   UploadFile file= new UploadFile();
   bool flag = file.upload_file(strPath, 25000, fileType);
   return Content("<script>window.alert('" + file.msg + "');window.top.close()</script>");
  }

Note:

1. The file path and file saving path are put in the configuration file. Of course, you can also put the file size and rename in the configuration file.

2. The script that returns to view pops up a prompt box first; Closing the window

3. According to your own needs to call UploadFile msg (Error Prompt), FullName (Full Name), FileName file name for operation

4. window. top. close () Close the current window of iframe. Please handle it by yourself for compatibility. There is no problem in my test.


Related articles: