File API in HTML5 (file/drag&/drop)

Keywords: Javascript Attribute xml encoding

1.file provides file-related information

(1) file objects

file objects generally come from three sources:

(1) The Filelist object returned after uploading the file is selected on the <input type='file'> element
 (2) Data Transfer objects generated by drag-and-drop operations;
(3) mozGetAsFile() API of HTML CanvasElement; (This article does not cover)

The first one discussed here is to get the file object:

let file = e.target.files[0];//Get the file object. When uploading multiple files (pictures), 0 represents the first

Properties:

lastModified: 1496803445926;//Last modification time of referenced files
lastModifiedDate: Wed Jun 07 2017 10:44:05 GMT+0800 (CST) {};//Date object for the last modification time of the referenced file
name: "many Y chart.svg";//Name of the file referenced
size: 1384;//Return file size
type: "image/svg+xml";//Multipurpose Internet Mail Extension Type Returning Files
webkitRelativePath: "";//Return File-related path s or URL s

(2) FileReader () object

FileReader() allows web applications to read asynchronously the contents of files (or raw data buffers) stored on the user's computer, specifying the files or data to read using File or Blob objects.

let reader = new FileReader();//create new object

Properties:

    error: error while reading a file;
    readyState: Indicates the current state of the FileReader object;
    result: The content of the read file is valid only after the read operation is completed. The data format depends on the read operation adopted.
               

Method:

  • abort(); abort the read operation

  • ReadAs Text (file, encoding); read in plain text, the data in result is a string.

  • ReadAsData URL (file); the result attribute will contain a string in data:url format.

  • ReadAs ArrayBuffer (file): The result attribute will contain an ArrayBuffer object.

  • ReadAs BinaryString (file): Binary source code for reading files.

Event Handler

  • onabort: Called when the read operation is aborted

  • onerror: Called when an error occurs in the read operation

  • onload: Called when the read operation completes successfully

  • Onload end: Called after onload or onerror when the read operation is complete (whether successful or unsuccessful)

  • Onload start: Called when the read operation is about to begin

  • onprogress: Called periodically during data reading

Following is an example of using FileReader to display user-selected files without being displayed in the background.

function handleFiles(files){
    if(files.length) {
       var file = files[0]; 
       var reader = new FileReader();
       reader.onload = function(e) {
           document.getElementById("filecontent").innerHTML = e.target.result;
       };  
       reader.readAsText(file); 
    }  
  } 

2. drag & drop (drag & drop)

(1) Make an element draggable

<img draggable="ture" />
After setting, draggable="ture" elements will be copied. Start the DnD function of HTML5 (that is, the dragstart event of the element can be triggered)

Dragable values:

 true, indicating that it can be dragged
 false, meaning that it cannot be dragged
 auto, default value, img and a tag with href attribute indicate drag-ability, while other tags indicate non-drag-ability.   
 Other values, indicating that they cannot be dragged

In most browsers, elements a and img are draggable by default, but for insurance, draggable attributes are preferred.

(2) Drag-and-drop related events:

  • Dragstart: Start dragging, triggered by the dragged element. Usually we record dragged element information at this step (ondrop is easy to process), where most of the settings of event.dataTransfer are configured. In addition, after triggering dragstart events, other elements mousemove,mouseover,mouseenter,mouseleave,mouseout events will not be triggered.

  • drag: Continuous triggering (from dragstart to dragend) during dragging, triggered by the dragged element

  • dragenter: Triggered when the dragged element enters the target element, triggered by the target element

  • dragover: Triggered when the dragged element moves on the target element. Note that it triggers after moving on the target element for a period of time. At this point, you can set the dropEffect value here to prevent default events (dragged elements are not allowed to be released or placed on other elements (that is, drop events cannot be triggered), triggered by the target element.

  • drop: Triggered when the dragged element is on the target element and the left mouse button is released. Cancel element dragover default behavior, such as opening links to certain elements

  • dragleave: Triggered when the dragged element leaves the target element, triggered by the target element

  • dragend: The drag-and-drop operation ends, triggered by the dragged element

(3) dataTransfer object

The dataTransfer object allows data to be stored on it, which makes it possible to transfer information between the dragged element and the target element.
 
Properties:

 dropEffect: The type of drag-and-drop operation determines how the browser displays the mouse shape. If the drag-and-drop behavior set here is no longer within the multiple drag-and-drop behavior set by the effectAllowed attribute, the drag-and-drop operation will fail. Possible values are copy, move, link, and none.
 effectAllowed: Specifies the permitted operations, with possible values of copy, move, link, copyLink, copyMove, linkMove, all, none, and uninitialized (default, equal to all, that is, all operations are allowed).
 Files: Contains a FileList object that represents the files involved in drag-and-drop. It is mainly used to process files that are dragged from the file system into the browser.
 types: The type of data stored in the DataTransfer object.
    

Method:

  • setData(format,data): Stores data on a dataTransfer object. The first parameter format is used to specify the type of data stored, such as text, url, text/html, and so on.

  • getData(format): Extract data from the dataTransfer object.

  • clearData(format): Clear the data stored in the dataTransfer object. If format parameters are specified, only data in that format is cleared, otherwise all data is cleared.

  • setDragImage(imgElement, x,y): Specifies the image to be displayed during the drag. By default, many browsers display a translucent version of the dragged element. The parameters imgElement must be an image element, not a path to the image. The parameters X and Y represent the position of the image relative to the mouse. Set the image that follows the mouse when dragging to replace the default element. If the image is not an image element, the element will be temporarily converted to a picture; it will only be called in the dragstart event.

$('#dragme').dragstart(function(event) {  
            var dt = event.dataTransfer;  
            dt.setDragImage($('img').attr("src", "images/img1.jpg")[0], -10, -10);  
            dt.setData("text/plain", "Welcome");  
        });

Example: Drag Web page elements

Part HTML

    <div class="gallery">
        <a id="1" draggable="true"><img src="images/1.jpg"></a>
        <a id="2" draggable="true"><img src="images/2.jpg"></a>
    </div>
    <div class="targetArea">
        <div class="target" id="drop_1" droppable="true"><h2>draggable</h2></div>
        <div class="target" id="drop_2"><h2>Do not drag and drop</h2></div>
    </div>
    <div style="clear:both"></div>

Part js

var addEvent = (function () {
  if (document.addEventListener) {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.addEventListener(type, fn, false);
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  }
})();

var dragItems;
updateDataTransfer();
var dropAreas = document.querySelectorAll('[droppable=true]');

// dragstart dragged element
function updateDataTransfer() {
  dragItems = document.querySelectorAll('[draggable=true]');
  for (var i = 0; i < dragItems.length; i++) {
    addEvent(dragItems[i], 'dragstart', function (event) {
      event.dataTransfer.setData('obj_id', this.id);
      return false;
    });
  }
}

// dragenter
addEvent(dropAreas, 'dragenter', function(e){
  // Prevent default events (by default, elements cannot be placed in other elements)
  if (e.preventDefault) {
    e.preventDefault();
  }
  return false;
});

// dragover target element
addEvent(dropAreas, 'dragover', function (event) {
  // Cancel the element dragover default behavior to make it drag-and-drop
  if (event.preventDefault) event.preventDefault();
  event.dataTransfer.dropEffect = 'move';
  this.style.borderColor = "#000";
  return false;
});

// dragleave target element
addEvent(dropAreas, 'dragleave', function (event) {
    this.style.borderColor = "#ccc";
    return false;
});

// Drop mouse releases, receives data on the drag-and-drop target and processes it
addEvent(dropAreas, 'drop', function (event) {
    // Cancel element dragover default behavior, such as opening links to certain elements
    if (event.preventDefault) event.preventDefault();

    var iObj = event.dataTransfer.getData('obj_id');
    var oldObj = document.getElementById(iObj);
    var oldSrc = oldObj.childNodes[0].src;
    oldObj.className += 'hidden';

    var oldThis = this;

    setTimeout(function() {
        oldObj.parentNode.removeChild(oldObj); 
        oldThis.innerHTML += '<a id="'+iObj+'" draggable="true"><img src="'+oldSrc+'" /></a>';
        updateDataTransfer();
        oldThis.style.borderColor = "#ccc";
    }, 500);

    return false;
});

Posted by simonsays on Wed, 02 Jan 2019 22:03:08 -0800