Do-it-Yourself Create Ajax picture upload (not on the Internet) _ajax related

Source: Internet
Author: User
Tags datetime httpcontext tojson

Today I need a picture upload plugin, but the internet does not provide a suitable for their own needs and easy to use. So he wrote one on his own hands.

Method 1, use only jquery code, not Third-party plug-ins. The code is as follows

<p> 
<label> upload photos </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,< C20/>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>

Disadvantage of this approach: since ie6\8\9\ does not support Formdata, this method does not support IE9 and the following versions

Method Two: 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 read  only= "readonly" type= "text" size= "/> </p> <div> <script type=" Text/javascript "> $ (Function () 
{$ ('. Inp_filetoupload '). Live ("change"), function () {//Now this already 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 ',//services for file uploads Secureuri:false request Address,//Whether a security protocol is required, generally set to false fileelementid:file_id,//File upload domain ID dataType: ' JSON ',//return value type is generally set to JSO n success:function (data, status)//Server Success Response processing function {if (Data.error = = 0) {$ ("#" + img_id). attr ("src", data.url); 
else {alert (data.message); 
}, Error:function (data, status, E)//server response failed processing function {alert (e); 
}) return false; } </script> </div> </div>


Description: This method currently tests support IE8/9, Google, compatibility is better than Method 1. Recommended Method 2

File Upload background processing code (asp.net version)

<%@ 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 save directory path String savepath = "attached/"; 
File save Directory URL String saveurl = aspxurl + "attached/"; 
Defines the file extensions allowed to be uploaded 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 = context; Httppostedfile Imgfile = context. 
request.files["Imgfile"]; if (Imgfile = = null) {showerror, select the file. 
"); String Dirpath = context. Server.MapPath (SavepaTH); if (! Directory.Exists (Dirpath)) {showerror ("Upload directory does not exist. 
"); String dirname = context. 
request.querystring["dir"]; 
if (String.IsNullOrEmpty (dirname)) {dirname = "image"; } if (!exttable.containskey (dirname)) {showerror ("directory name is not correct.") 
"); 
String fileName = imgfile.filename; String Fileext = path.getextension (fileName). 
ToLower (); if (Imgfile.inputstream = null | | imgFile.InputStream.Length > MaxSize) {showerror ("Upload file size exceeds limit.") 
"); } if (String.IsNullOrEmpty (fileext) | | Array.indexof ((((String) exttable[dirname]). Split (', '), fileext.substring (1). ToLower () = = = 1) {showerror ("The Upload file extension is an disallowed extension.") \ nthe only "+ ((String) exttable[dirname]) +" format is allowed. 
"); 
//Create 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 {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.