Here is a screenshot of the wifi book transfer using iReader. You can either click the blue “Select File” button to select the file or drag the file directly to this interface. Personally, I prefer the drag-and-upload method. A web page that allows you to select files but doesn’t support drag and drop uploads always strikes me as primitive.

This is a very common feature, so how does it work? Today we will write a small Demo to demonstrate!

This function is achieved mainly by the Drap API of the browser. Many of you may not know that when you drag a file on your computer and place a target, this also triggers the Drag event.

The code!

let dropTarget = document.getElementById('app');

function handleEvent(event) {
  event.preventDefault()

  if (event.type === 'drop') {
    const files = event.dataTransfer.files;
    const reader = new FileReader();
    
    reader.readAsDataURL(files[0]);

    reader.onload = () = > {
      dropTarget.style.backgroundImage = reader.result;
      dropTarget.style.backgroundImage = `url(${reader.result}) `   
    }
  }
}

dropTarget.addEventListener("drop", handleEvent);
dropTarget.addEventListener("dragenter", handleEvent);
dropTarget.addEventListener("dragover", handleEvent);
Copy the code

At the end of the code, why do we bind three events? Is to cancel the default event for the drag procedure.

All we really need is ‘drop’, so we make the if judgment.

FileReader objects read files asynchronously. Although the result is in the Result property of the FileReader object, the actual result is not retrieved until the onload event is triggered. Init, the onload property of the FileReader object is null, so we need to initialize this function ourselves.

Finally, there’s the readAsDataURL API. It stores the URL of the content data in the Result property of the FileReader.

Sometimes we don’t need to read the content, like the one above, we just need to get a URL for it that we can display in the tag. In this case, we don’t need to use the FileReader, more simple method: window. URL. CreateObjectURL, is it returns a pointer to a memory address of a string.

import "./styles.css";

let dropTarget = document.getElementById('app');

function handleEvent(event) {
  event.preventDefault()

  if (event.type === 'drop') {
    // The following three lines are changed
    const files = event.dataTransfer.files;
    const url = window.URL.createObjectURL(files[0]);
    dropTarget.style.backgroundImage = `url(${url}) `
  }

}

dropTarget.addEventListener("drop", handleEvent);
dropTarget.addEventListener("dragenter", handleEvent);
dropTarget.addEventListener("dragover", handleEvent);
Copy the code

I’m going to share this tip with you today.