Upload images asynchronously using Ajax and Jquery. form,

Source: Internet
Author: User
Tags thread stop

Upload images asynchronously using Ajax and Jquery. form,
I. Preface

Third-party plug-ins used for image uploading,UploadifyThis should be a lot of use, and I have also used other features. I also admire the functions of others while making it easier for me. Think about it. I will only use other people's things, and I will never learn much. Please try it by yourself.


Ii. Results

Let's take a look at the results. This is what we did during interface development. It is simple, but we only need to implement functions.

(1): this is before the upload.

(2): this is a picture not selected.

(3): select the image.

(4): This is the effect after uploading. The image path is returned and displayed on the page. Because ajax is used, the page is not refreshed.

Iii. Implementation Method

(1): aspx page code

<Input id = "file_temporaryImage" type = "file" name = "file_temporaryImage"/> <div id = "div_temporaryImage"> </div> <br/> <input id =" btn_temporary "type =" button "value =" Upload temporary material "onclick =" javascript: temporaryMedia (); "/>

(2): js method used

/***** Pony upload material management at 10:26:17 on April 9, April 29, 2015 ** // *********************** upload temporary material Start ** * *************************/function TemporaryMedia () {// var image0 = $ ("input [name = 'file _ temporaryimage']"). val (); // determine whether the image var image is selected in the upload control =$ ("# file_temporaryImage "). val (); if ($. trim (image) = "") {alert ("select an image! "); Return;} // url var actionUrl =" ImageUpload. ashx "; // start ajax operations $ (" # form1 "). ajaxSubmit ({type: "POST", // ype: "json", // return result format url: actionUrl, // request address data: {"action ": "TemporaryImage"}, // request data success: function (data) {// function if (data. status = "warning") {// returns the warning alert (data. msg);} else if (data. status = "success") {// return success $ ("# div_temporaryImage "). append (" <span> temporary clip mediaId:" + data. uploadmsg. media_id + "</span>") ;}}, error: function (data) {alert (data. msg) ;}, // function async for request failure: true });} /******************** upload temporary material End *************** **************/

(3): The general processing program code used.

Using System; using System. IO; using System. text; using System. web; using WeiXin_Web.Common; using WX_Tools; using WX_Tools.Entites; namespace WeiXin_Web {/// <summary> // ImageUpload abstract description /// </summary> public class ImageUpload: IHttpHandler {private HttpContext _ httpContext; public void ProcessRequest (HttpContext context) {_ httpContext = context; // context. response. contentType = "text/plain"; // co Ntext. response. write ("Hello World"); // obtain the request string requestAction = context. request. form ["action"]; switch (requestAction) {// temporary image material case "TemporaryImage": TemporaryMeidaUpload (); break ;}} // reply to message status private enum status {error, success, warning} // <summary> // upload temporary materials /// </summary> private void TemporaryMeidaUpload () {// return format: {"status": "error, success, warning", "msg": ""} // string result = "{\" st Atus \ ": \" {0} \ ", \" msg \ ": \" {1 }\"}"; try {// obtain the file HttpPostedFile upfile = _ httpContext Based on the name of the foreground html. request. files ["file_temporaryImage"]; if (upfile = null) {ResponseWriteEnd (status. warning. toString (), "No file selected");} // original file name string oldMediaName = upfile. fileName; // The Name Of The suffix after the file string oldMediaExtension = Path. getExtension (oldMediaName); // determines whether the file format meets the requirements if (! OldMediaExtension. ToLower (). Equals (". jpg") {ResponseWriteEnd (status. warning. ToString (), "upload a jpg file! "); Return;} // determine whether the file size meets the requirements if (upfile. contentLength> = (1024*1024*1) {ResponseWriteEnd (status. warning. toString (), "please upload files within 1 MB! "); Return;} string imgName = DateTime. now. toString ("yyyy-MM-dd-HH-ss") + DateTime. now. ticks; bool flag = false; try {upfile. saveAs (_ httpContext. server. mapPath ("/Upload/" + imgName + ". jpg "); flag = true;} catch (Exception e) {// write log} if (flag) {// return json ResponseWriteEnd (status. success. toString (), "/Upload/" + imgName + ". jpg ");} else {File. delete (_ httpContext. server. mapPath ("/Upload/" + I MgName + ". jpg"); ResponseWriteEnd (status. warning. ToString (), "An error occurred while saving the image. The image has been deleted. ") ;}} Catch (Exception EX_NAME) {ResponseWriteEnd (status. error. toString (), EX_NAME.ToString ());}} /// <summary> /// output method /// </summary> /// <param name = "status"> </param> /// <param name = "msg"> </param> private void ResponseWriteEnd (string status, string msg, string uploadMsg = "") {StringBuilder stringBuilder = new StringBuilder (); stringBuilder. append ("{"); stringBuilder. append ("\" status \ ":"); strin GBuilder. appendFormat ("\" {0} \ ",", status); stringBuilder. append ("\" msg \ ":"); stringBuilder. appendFormat ("\" {0} \ ",", msg); stringBuilder. append ("\" uploadmsg \ ":"); stringBuilder. appendFormat ("{0}", uploadMsg); stringBuilder. append ("}"); _ httpContext. response. write (stringBuilder. toString (); // _ httpContext. response. end (); this method will cause a thread STOP error. _ HttpContext. ApplicationInstance. CompleteRequest ();} public bool IsReusable {get {return false ;}}}}

(4): Introduce jquery. form. js.


4. Download source code

Because this is part of the code in interface development, the complete interface development Code address is provided here. I have hosted it on github and you can download it, you can also write this project together.

Https://github.com/anyangmaxin/WeiXin

5. Welcome to the. net technology exchange group.


Welcome to the. net technology exchange group.


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.