Welcome to my personal blog to share front-end techniques, interview questions, interview techniques and more

Now that we’ve learned about HTML’s native drag & drop, it’s time to think about what it can be used for, when it can be used, what scenarios it can be used in, and so on

Scenario analysis

When we successfully register an account, general websites will ask us to upload our user profile picture, or the id card picture will be uploaded during the real-name authentication. At this time, we can use the file attribute provided by input to select local files for uploading.

Let’s think again, in the case of computer, when the user opens the file selection box and then looks for the folder corresponding to the picture, and then selects the file, will it be a little trouble? Can we let the user find the image file and upload it directly? The answer is yes.

How to do

After all this analysis, we can try to use the drag and drop provided by HTML5 to make the target element add file-reading capability, and then use Ajax for image uploading.

Talk about the technologies we need to use:

  • Drag & Drop: HTML5 drag-based event mechanism
  • File API: File API includes FileList, Blob, File, FileReader and URI scheme. This article mainly explains the FileList and FileReader interfaces used in drag-and-drop uploads.
  • FormData: FormData is a new interface based on XMLHttpRequest Level 2 that makes it easy for Web applications to emulate Form data. Most importantly, it supports binary streaming of file data so that you can use it to send file data back to AJAX.

HTML5 drag events

Drag & Drop is a Drag and Drop event, and it is a Drag and Drop event. It is a Drag and Drop event, and it is a Drag and Drop event

var oDragWrap = document.body;

/ / in
oDragWrap.addEventListener(
  "dragenter".function(e) {
    e.preventDefault();
  },
  false
);

/ / off
oDragWrap.addEventListener(
  "dragleave".function(e) {
    dragleaveHandler(e);
  },
  false
);

// Drag around, be sure to note that the dragover event must clear the default event
// Otherwise, the drop event will not be triggered
oDragWrap.addEventListener(
  "dragover".function(e) {
    e.preventDefault();
  },
  false
);

/ / throw
oDragWrap.addEventListener(
  "drop".function(e) {
    dropHandler(e);
  },
  false
);

var dropHandler = function(e) {
  // This is what happens when you drag and drop a local image onto the page
};
Copy the code

Get File data HTML5 File API

The FileReader interface in the File API. As part of the File API, FileReader is dedicated to reading files. The FileList interface in the File API is a list of local files in the form of . The other is the name of the e.datatransfer. files drag-drop event.

var fileList = e.dataTransfer.files;
Copy the code

The files method retrieves an array of drag files, each file occupies an index of the array, and returns Null if the index does not contain file data. You can get the number of files through the length attribute.

var fileNum = fileList.length;
Copy the code

The thing to notice about drag upload is that you need to judge two conditions

  1. Drag files instead of page elements
  2. Drag and drop images instead of other types of filesfile.typeProperty gets the type of the file
// Check if the file is being dragged to the page
if (fileList.length === 0) {
  return;
}

// Check if the file is a picture
if (fileList[0].type.indexOf("image") = = =- 1) {
  return;
}
Copy the code

Let’s take a look at dragging images and preview them on the page in combination with the previous drag event

var dropHandler = function(e) {
  e.preventDefault(); // Get the list of files

  var fileList = e.dataTransfer.files;

  // Check if the file is being dragged to the page
  if (fileList.length == 0) {
    return;
  }

  // Check if the file is a picture
  if (fileList[0].type.indexOf("image") = = =- 1) {
    return;
  }

  // Instantiate the File Reader object
  var reader = new FileReader();
  var img = document.createElement("img");

  reader.onload = function(e) {
    img.src = this.result;
    oDragWrap.appendChild(img);
  };
  reader.readAsDataURL(fileList[0]);
};
Copy the code

When you are done, you should be able to successfully drag and drop the image preview. When you look at the IMG tag, the SRC attribute of the IMG is an extremely long file binary. When you need a lot of these IMG elements, it is recommended to take the display area out of the document stream and make it absolutely positioned to reduce reflow on the page

Uploading images with AJAX

Now that you have the image data dragged to the Web page, the next step is to send it to the server side.

conclusion

  1. Listen to drag: Listens for drag events on page elements, including:dragenter,dragover,dragleavedrop.Be sure to willdragoverThe default event of thedropThe event. To drag and drop elements on a page, add attributes to themdraggable="true"
  2. Get the drag fileIn:dropThe event is triggered and passede.dataTransfer.filesGets a list of drag files,Be sure to willdropCancel the default event, otherwise the file will be opened by defaultlengthProperty to get the number of files,typeProperty to get the file type
  3. Read image data and add preview images: instantiateFileReaderObject through whichreadAsDataURL(file)Method gets the binary stream of a file and listens for itonloadEvents,e.resultAssigns the SRC attribute to img, and finally adds the image to the DOM
  4. Sending picture data

Hope to read this article you have help, have inspiration, if there is not enough, welcome to criticize the exchange!

Welcome to my personal blog to share front-end techniques, interview questions, interview techniques and more

Hard to sort out for a long time, but also hope to manually praise encouragement ~


‘Extract’ is not simply “paste -> copy”, but eye to, hand to, heart to beat down every word.

Blog statement: all reprinted articles and pictures are only used for the author’s own collection and study purposes. If requested or deemed appropriate, attribution and source will be given. If you do not want a work to be re-used, please inform the site in time, the site will be deleted in time.