Self-built ajax Image Upload (not available on the Internet)

Source: Internet
Author: User
Tags tojson

Today, I need an Image Upload plug-in, but I have not provided an Image Upload plug-in that suits my needs and is easy to use. So I wrote one by myself.

Method 1: only use jquery Code, without third-party plug-ins. The Code is as follows:

<P> <label> upload an image </label> <input class = "ke-input-text" type = "text" id = "url" value = "" readonly =" readonly "/> <input type =" button "id =" uploadButton "value =" Upload "/> </p> <script type =" text/javascript ">$ (function () {$ ('. inp_fileToUpload '). change (function () {var formdata = new FormData (); var v_this = $ (this); var fileObj = v_this.get (0 ). files; url = "/upload/upload_json.ashx"; // var fileObj = document. getElementById ("fileToUpload "). files; formdata. append ("imgFile", fileObj [0]); jQuery. ajax ({url: url, type: 'post', data: formdata, cache: false, contentType: false, processData: false, dataType: "json", success: function (data) {if (data. error = 0) {v_this.parent (). children (". img_upload "). attr ("src", data. url); // $ ("# img "). attr ("src", data. url) ;}}); return false ;}); </script>

Disadvantages of this method: Because IE6 \ 8 \ 9 \ does not support formdata, this method does not support IE9 or earlier versions

Method 2: Use the ajaxfileupload. js plug-in
Ajaxfileupload. js
Html code:

<P> <label> ajax upload </label> <input type = "file" name = "fileToUpload" id = "fileToUpload" class = "inp_fileToUpload" multiple = "multiple "/>  </p> <p> <label> latest modifier: </label> <input readonly = "readonly" type = "text" size = "30"/> </p> <div> <script type = "text/javascript"> $ (function () {$ (". inp_file ToUpload "). live (" change ", function () {// now this applies to multiple file forms. AjaxFileUpload ($ (this ). attr ("id"), $ (this ). parent (). children (". img_upload "). attr ("id") ;}) function ajaxFileUpload (file_id, img_id) {jQuery. ajaxFileUpload ({url: '/upload/upload_json.ashx', // server-side request address used for file upload secureuri: false, // whether security protocol is required. Generally, this parameter is set to false fileElementId: file_id, // the ID of the file upload field dataType: 'json', // The type of the returned value is generally set to json success: function (data, status) // The server responds to the processing function {if (data. error = 0) {$ ("#" + img_id ). attr ("src", data. url);} else {alert (data. message) ;}}, error: function (data, status, e) // server response failure handler {alert (e) ;}}) return false ;} </script> </div>


Note: This method currently supports IE8/9, Google, and is better compatible than method 1. Recommended method 2

File Upload background processing code (asp.net)

<% @ Webhandler Language = "C #" class = "Upload" %> using System; using System. collections; using System. web; using System. IO; using System. globalization; using LitJson; public class Upload: IHttpHandler {private HttpContext context; public void ProcessRequest (HttpContext context) {String aspxUrl = context. request. path. substring (0, context. request. path. lastIndexOf ("/") + 1); // file storage directory path String savePat H = "attached/"; // URL of the file storage directory String saveUrl = aspxUrl + "attached/"; // defines the file extension Hashtable extTable = new Hashtable (); extTable. add ("image", "gif, jpg, jpeg, png, bmp"); extTable. add ("flash", "swf, flv"); extTable. add ("media", "swf, flv, mp3, wav, wma, wmv, mid, avi, mpg, asf, rm, rmvb"); extTable. add ("file", "doc, docx, xls, xlsx, ppt, htm, html, txt, zip, rar, gz, bz2 "); // maximum file size: int maxSize = 1000000; this. context = c Ontext; HttpPostedFile imgFile = context. Request. Files ["imgFile"]; if (imgFile = null) {showError ("select a file. ");} String dirPath = context. Server. MapPath (savePath); if (! Directory. Exists (dirPath) {showError ("the upload Directory does not exist. ");} String dirName = context. Request. QueryString [" dir "]; if (String. IsNullOrEmpty (dirName) {dirName =" image ";} if (! ExtTable. ContainsKey (dirName) {showError ("the directory name is incorrect. ");} String fileName = imgFile. fileName; String fileExt = Path. getExtension (fileName ). toLower (); if (imgFile. inputStream = null | imgFile. inputStream. length> maxSize) {showError ("the size of the uploaded file exceeds the limit. ");} If (String. isNullOrEmpty (fileExt) | Array. indexOf (String) extTable [dirName]). split (','), fileExt. substring (1 ). toLower () =-1) {showError ("the file extension is not allowed. \ N only supports the "+ (String) extTable [dirName]) +" format. ") ;}// Create the folder dirPath + = dirName +"/"; saveUrl + = dirName +"/"; if (! Directory. exists (dirPath) {Directory. createDirectory (dirPath);} String ymd = DateTime. now. toString ("yyyyMMdd", DateTimeFormatInfo. invariantInfo); dirPath + = ymd + "/"; saveUrl + = ymd + "/"; if (! Directory. exists (dirPath) {Directory. createDirectory (dirPath);} String newFileName = DateTime. now. toString ("yyyyMMddHHmmss_ffff", DateTimeFormatInfo. invariantInfo) + fileExt; String filePath = dirPath + newFileName; imgFile. saveAs (filePath); String fileUrl = saveUrl + newFileName; Hashtable hash = new Hashtable (); hash ["error"] = 0; hash ["url"] = fileUrl; context. response. addHeader ("Content-Type", "text/html; charset = UTF-8"); context. response. write (JsonMapper. toJson (hash); context. response. end () ;}private void showError (string message) {Hashtable hash = new Hashtable (); hash ["error"] = 1; hash ["message"] = message; context. response. addHeader ("Content-Type", "text/html; charset = UTF-8"); context. response. write (JsonMapper. toJson (hash); context. response. end () ;}public bool IsReusable {get {return true ;}}}

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.