The form upload function enables asynchronous upload of ajax files and asynchronous upload of ajax files

Source: Internet
Author: User

The form upload function enables asynchronous upload of ajax files and asynchronous upload of ajax files

In the project, user uploads are always indispensable. Below we will mainly list form uploads and ajax uploads! Note: context. Request. Files is not suitable for operations on large Files. The following describes how to upload small Files!

Download resources:

I. jQuery official: https://jquery.com/download/

1. Form upload:

Html client:

<Form action = "upload. ashx "method =" post "enctype =" multipart/form-data "> select a file: <input type = "file" name = "file1"/> <br/> <input type = "submit" value = "Upload"/> </form>

General handler Server:

Public void ProcessRequest (HttpContext context) {context. response. contentType = "text/plain"; HttpPostedFile file1 = context. request. files ["file1"]; helper. uploadFile (file1 ,"~ /Upload/"); // call context. Response. Write (" OK ") for the corresponding method; // prompt that the execution is successful}

Encapsulation of uploaded code:

/// <Summary> /// upload an image /// </summary> /// <param name = "file"> file submitted through form </param>/ // <param name = "virpath"> virtual path of the file to be saved </param> public static void uploadImg (HttpPostedFile file, string virpath) {if (file. contentLength> 1024*1024*4) {throw new Exception ("file cannot be greater than 4 M");} string imgtype = Path. getExtension (file. fileName); if (imgtype! = ". Jpg" & imgtype! = ". Jpeg ") // limits the Image type {throw new Exception (" Upload jpg or JPEG Image ");} using (Image img = Bitmap. fromStream (file. inputStream) {string savepath = HttpContext. current. server. mapPath (virpath + file. fileName); img. save (savepath );}} /// <summary> /// upload a file /// </summary> /// <param name = "file"> file submitted through form </param>/ // <param name = "virpath"> virtual path for saving the file </param> public static void uploadFile (HttpPostedFile file, String virpath) {if (file. contentLength> 1024*1024*6) {throw new Exception ("file cannot exceed 6 M");} string imgtype = Path. getExtension (file. fileName); // imgtype restricts the uploaded files if (imgtype! = ". Zip" & imgtype! = ". Mp3 ") {throw new Exception (" only uploads zip files and rar files .... file ");} string dirFullPath = HttpContext. current. server. mapPath (virpath); if (! Directory. Exists (dirFullPath) // If the folder does not exist, create the folder {Directory. CreateDirectory (dirFullPath);} file. SaveAs (dirFullPath + file. FileName );}

Ii. asynchronous upload of Ajax files:

Note: Why do I need ajax to upload a form? The whole page is refreshed during form upload! Ajax asynchronous upload can only refresh the local location. Let's take a look at ajax upload!

Html client:

<Head> <script src = "jquery-2.1.4.js"> </script> <script> $ (function () {$ ("# upload "). click (function () {$ ("# imgWait "). show (); var formData = new FormData (); formData. append ("myfile", document. getElementById ("file1 "). files [0]); $. ajax ({url: "upload. ashx ", type:" POST ", data: formData,/*** must be false to automatically add the correct Content-Type */contentType: false, /*** it must be false to avoid jQuery's default formdata Processing * XMLHttpRequest will Correct Processing of formdata */processData: false, success: function (data) {if (data. status = "true") {alert ("uploaded successfully! ");} If (data. status = "error") {alert (data. msg) ;}$ ("# imgWait "). hide () ;}, error: function () {alert ("Upload Failed! "); $ (" # ImgWait "). hide () ;}}) ;}); </script> 

General handler Server:

Public void ProcessRequest (HttpContext context) {context. response. contentType = "text/html"; if (context. request. files. count> 0) {HttpPostedFile file1 = context. request. files ["myfile"]; helper. uploadFile (file1 ,"~ /Upload/"); // The WriteJson (context. response, "true", "");} else {WriteJson (context. response, "error", "select the file to upload ");}}

Json code encapsulation:

public static void WriteJson(HttpResponse response,      string status1, string msg1, object data1 = null)    {      response.ContentType = "application/json";      var obj = new { status = status1, msg = msg1, data = data1 };      string json = new JavaScriptSerializer().Serialize(obj);      response.Write(json);    }

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.