Application Brief: This article mainly describes how to paste the image directly in the front-end div and upload it to the server, including dragging and dropping the picture file into the Div.
Application Scenario Description: Use QQ or other cut diagram software, in the specified div Ctrl + V paste and display, click the Upload button, the image uploaded to the server. Similar to the implementation of this feature of the site is known, strongly recommend the blog Park to achieve this function, write a blog when inserting pictures more convenient.
Applicable environment: This code is currently applicable to Google Browser, other browsers need a little improvement can be, the problem is not big.
Development environment: VS2015 MVC
Don't talk nonsense, start it:
1: First create HTML elements, we want to paste the picture is displayed in the id=pasteimg Div, note the need to set the div contenteditable= "true" property can be edited oh.
< div id = "pasteimg" style = "width:400px;height:300px;border:dashed" contenteditable = "true" ></ div > < button style = "width:30px;height:20px;" ID = "Btngo" > upload picture </ button >
2: Write JS code: Bind paste Event Upload image server
Window.onload =function () { functionpaste_img (e) {if(E.clipboarddata &&e.clipboarddata.items) {varImagecontent = E.clipboarddata.getdata (' image/png ')); Ele=E.clipboarddata.items for(vari = 0; i < ele.length; ++i) {
Paste Pictureif(Ele[i].kind = = ' file ' && ele[i].type.indexof (' image/')!==-1) { varBlob =Ele[i].getasfile (); Window. URL= window. URL | |Window.webkiturl; varBloburl =window. Url.createobjecturl (BLOB); //displayed in Div, this is the local picture data that is displayed, and is not uploaded to the server varnew_img = document.createelement (' img '); New_img.setattribute (' SRC ', Bloburl); New_img.setattribute (' BLOBData ', BLOB);
//Move div cursor to new element behind Inserthtmlatcaret (NEW_IMG);
Upload directly, of course, you can also not upload, you can click the button in the upload
Uploadimg (BLOB); }
Paste TextElse if(Ele[i].kind = = = "string" && ele[i].type.indexof (' Text/plain ')! =-1) {
//Paste text callback function
Ele[i].get Asstring (
function (str) { inserthtmlatcaret (document.createTextNode (str));//Insert text at cursor and move the cursor to the new position }) } elsereturn;} } Else { alert (' unsupported browser ');} }
//Bind paste event document.getElementById (functionreturnfalse;};
}
3: The following is the Inserthtmlatcaret method, the main implementation of the DIV move cursor position, not directly skip this step
//After the chat box has inserted text or other elements, move the cursor to the latest positionfunctionInserthtmlatcaret (childelement) {varsel, Range; if(window.getselection) {//IE9 and Non-ieSEL =window.getselection (); if(Sel.getrangeat &&sel.rangecount) {range= Sel.getrangeat (0); Range.deletecontents (); varel = document.createelement ("div"); El.appendchild (childelement); varFrag =document.createdocumentfragment (), node, lastnode; while(node =el.firstchild)) {Lastnode=frag.appendchild (node); } range.insertnode (Frag); if(lastnode) {range=Range.clonerange (); Range.setstartafter (Lastnode); Range.collapse (true); Sel.removeallranges (); Sel.addrange (range); } } } Else if(document.selection && Document.selection.type! = "Control") { //IE < 9 //Document.selection.createRange (). pastehtml (HTML); }}
4: Upload image data with XHR
varCREATESTANDARDXHR =function () { Try { return Newwindow. XMLHttpRequest (); } Catch(e) {return false; } }; varCREATEACTIVEXHR =function () { Try { return NewWindow. ActiveXObject ("Microsoft.XMLHTTP"); } Catch(e) {return false; } }; varXHR; functioncreatexhr () {vartemp = CREATESTANDARDXHR () | |createactivexhr (); if(Window. Xdomainrequest = = =undefined) { returntemp; } Else { return Newxdomainrequest (); }}//Front-end upload Methodfunctionuploadimg (obj) {xhr=createxhr (); if(XHR) {Xhr.onerror=err; Xhr.ontimeout=Timeo; Xhr.onprogress=Progres; Xhr.onload=Loadd; Xhr.timeout=Timeo; } Else{alert ("Failed to create"); } //the data sent varFD =NewFormData (); Fd.append ("Image", obj, "imgtest.png"); //Send using AjaxXhr.open (' POST ', ' Home/uploadfun ',true);///The second parameter is the server handles the action, each language provides a different way, I this is. NET MVC background processing, the concrete method see step 5 xhr.send (FD); } functionerr () {//alert ("XDR onerror"); } functionTimeo () {//alert ("XDR ontimeout"); } functionLoadd () {//alert ("Upload complete"); //alert ("Got:" + xhr.responsetext); } functionProgres () {//alert ("XDR onprogress"); } functionStopdata () {xhr.abort (); }
5: Background to receive image data processing methods, I use the. NET MVC background, according to their own language does not use the corresponding processing method
Public classHomecontroller:controller { PublicActionResult Index () {returnView (); } [HttpPost] PublicActionResult Uploadfun () {if(Request.Files.Count >0) { varFile = request.files[0]; if(File! =NULL&& file. ContentLength >0) { //Verifying file Formats varExtension =path.getextension (file. FileName); //if (Extension! = ". xls" && extension! = ". xlsx")//{ //}
Upload a successful image URLvarFilefullpath = Path.Combine (Request.mappath ("~/uploads"), DateTime.Now.ToString ("YYYYMMDDHHMMSS") +path.getfilename (file. FileName)); File. SaveAs (Filefullpath); returnContent ("Upload Success! URL:"+Filefullpath, "Text/plain");
}
}
returnNewJsonresult ();
}
}
6: Extension, drag image file to div direct send
//Here are the drag eventsDocument.addeventlistener ("DragEnter",function(e) {e.stoppropagation (); E.preventdefault ();},false);d Ocument.addeventlistener ("DragLeave",function(e) {e.stoppropagation (); E.preventdefault ();},false);d Ocument.addeventlistener ("DragOver",function(e) {e.stoppropagation (); E.preventdefault ();},false);d Ocument.addeventlistener ("Drop",function(e) {e.stoppropagation (); E.preventdefault (); Handlefiles (e.datatransfer.files);},false);//Drag-and- drop file handling eventsHandlefiles =function(files) { for(vari = 0; i < files.length; i++) { varFile =Files[i]; //if the stall comes in, the picture file is displayed if(File.type.match (/image*/)) { $("#pasteImg"). focus ();
var blob =
New_img.setattribute (' BLOBData ', blob);
Move the DIV cursor to the new element behind Inserthtmlatcaret (NEW_IMG);
Upload directly, of course, you can also not upload, you can click the button in the upload
Uploadimg (BLOB);
elsecontinue;}} }
7: The implementation of CTRL + V paste the picture and send the server, also has the ability to drag the picture file and send the server
Divergence: Something that can be uploaded to a file
To be solved: Internet Explorer and Firefox can paste images and files directly, displaying data instead of BLOB format.
div paste the picture and upload the server div to drag the picture file and upload the server