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 HTML code of the ajaxfileupload. js plug-in:
<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); // path of the file storage directory string savepath = "ATT Ached/"; // 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 = context; 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 ;}}}