MVC file Control no flush asynchronous upload Operation Source code _ Practical Skills

Source: Internet
Author: User
Tags datetime file size file upload flush httpcontext int size

Objective

Uploading files should be a very common and essential operation, and there are many uploaded controls available on the Web. A problem was encountered today: the input control file could not be asynchronously uploaded without a refresh. It really feels awkward. So try this to deal with it. Mainly divided into three parts: Upload class encapsulation, HTML input Control file processing and background controller calls.

Upload Package class:

There are two main features of this class, some simple filtering and file renaming operations.

Filtering for files includes:

File type, file size

Renaming:

Where the default is no rename operation, where renaming defaults to time string DateTime.Now.ToString ("Yyyymmddhhmmss")

File Address:

can be customized. Both the relative address and the absolute address are OK.

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 information 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" > File size </param>///<param name= "filetype" > File type </param>/// <param name= "Files" >file uploaded file </param>///<param name= "Isrename" > whether duplicate name </param>///< 
  Returns></returns> public bool Upload_file (string filepath, int size, string[] filetype, bool Isrename = False)
   {filepath = Server.MapPath (filepath); If the folder does not exist, create an 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 = "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 way to upload a file is not an introduction to this. Look at the code comments should be well understood.

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

Note: Because the MVC upload file input control file does not support asynchronous no refresh upload, so use the call jump to the iframe of the way to upload no refresh operation.

The above page is the HTML definition of the upload control. There are a few things to notice.

1.enctype= "Multipart/form-data" must be added, the form enctype= "Multipart/form-data" 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, and only the multipart/form-data can be used to complete the transfer of file data and perform the following actions. Enctype= "Multipart/form-data" is the uploading of binary data; The value of the input in the form is passed in the form of 2.

The name of 2.form should be added

3. Submit button is submit, of course, if you want to write JS set to button also become. This is nothing to say.

4.iframe style= "Display:none"

The above is the entire layout and submit uploaded files to the background, and jump to the Ifrom, next is to accept the call to upload the file method. Then in the IFRAME page prompts upload results, and then close the IFRAME.

Background code:

 [HttpPost]
  Public ActionResult FileUpload ()
  {
   //Get support upload file format from 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. File path, file save path in the configuration file, of course, you can also file size, whether the renaming are placed in the configuration file.

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

3. According to your own needs to call UploadFile MSG (error hint), FullName (full name), filename file name to operate

4.window.top.close () to close the current iframe window, for compatibility, please take care of yourself, I tested no problem.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.