Drag-and-drop image upload to server

Source: Internet
Author: User

Today, a new problem, is the picture dragged upload to the server, in general, we will think of using Ajax, but now the problem is that Ajax default is no commit event, that is, we drag and drop upload pictures, we can not send the uploaded image information to the server, this time we have to simulate the form form of the submission.

Since to upload, here is the first thing to talk about is the picture dragged upload.

Odiv.ondrop = function (e) {e.preventdefault (); //Get dragged over objects, set of File objects var fs = E.datatransfer.files; //If the file selected in the form field is in the Files tab, use form[form name].files[0] to get the file object collection Console.log (fs.length); Print length
//Cyclic multi-file drag and drop upload
for (var i = 0; I <FS . length; i++) {
var _type = Fs[i].type; Console.log (_type); //Get file type if (_type.indexof (' image ')! =-1) { console.log (fs[i].size); //File Size control
   FileReader (); //Read File object
Reader.readasdataurl (Fs[i]);   //read as Dataurl, no return value   
Triggered when the read succeeds, this.result the file data for reading
         
if (reader.error) {

}else{


  

Drag and drop the picture, now to use the Ajax simulation form submission Event (PS: The following code is placed in the file after the successful reading function, that is, the Render.onload event inside):

XHR = new XMLHttpRequest (); Xhr.open ("Post", "Http://www.xunkanimg.top/upload", true); Xhr.setrequestheader ("X-requested-with", "XMLHttpRequest"); var fd = new FormData (); Fd.append (' file ', fs[0]);  //file equivalent to input type=file, followed by fs[0] is the picture information to be submitted Xhr.onreadystatechange = function () {    if (xhr.readystate = = 4 && Xhr.status = = +) {        //Ajax callback function    }}   xhr.send (FD);            

Drag-and-drop image upload to server

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.