JS HTML5 Drag upload picture preview _javascript Tips

Source: Internet
Author: User

1. Document API: (File API)

Each file that is selected by a form control of type file is a filename object, and the FileList object is a list of the collections of these file objects, representing all the files selected. The file object inherits from the Blob object, which represents the binary raw data, provides the slice method, and can access the raw block of data inside the byte. In summary, the file object contains the Flielist object, and the file object inherits from the Blob Object!

Related property relationships for each object:

FileReader Interface:
As the figure shows: HTML5 also provides a filereader interface for reading files into memory and reading the data in the file.

var reader=new filereader ();

The interface has a total of four methods and six events:
readasbinarystring (file): Read files as binary
readasdataurl (file): Reading files Dataurl
Readastext (file,[encoding]): Read file as text
About (None): Break file read
--------------------------------------------------------------------------------
onabort: Trigger when reading file interrupts
onerror: Trigger when Error reading file
Onloadstart: Trigger when reading file start
onprogress: Always triggers when reading from a file
onload: Trigger when reading a file successfully
onloadend: Trigger at end of read file (both success and failure will be triggered)
The above event parameter E has E.target.result or this.result points to read results!

2. Drag-and-drop APIs:

Drag-and-drop properties: Sets the Dragable property of the element that needs to be dragged to True (dragable= "true")!img element and a element can be dragged and dropped by default.

Drag-and-drop events: (Divided into drag-and-drop element events and target element events)

Drag-and-drop element events:
DragStart: Drag before triggering
drag, drag-and-drop before and after the end, continuous triggering
Dragend, drag-and-drop end trigger
Target Element Event:
DragEnter, enter target element trigger
DragOver, enter the target, leave the target, and trigger continuously
DragLeave, leave the target element trigger
drop, releasing the mouse trigger on the target element
But! Note that the default behavior is blocked in the DragOver and drop events in the target element (refused to be dragged), otherwise the drag-and-drop cannot be implemented!

--------------------------------------------------------------------------------

DataTransfer object: The data that is specifically used to hold drag-and-drop, can be set to the DataTransfer property of a drag-and-drop event.

3 Properties:
effectallowed: Set cursor style (none, copy, Copylink, Copymove, Link, linkmove, move, all and uninitialized)
effectallowed: Set the visual effect of a drag-and-drop operation
types: Type of data stored, pseudo array of strings
files: Gets the externally dragged file, returns a filelist list, Fileslist has a type attribute, returns the file
4 methods:
SetData (): Sets the Data key and value (must be a string)
GetData (): Get the data, according to the key value, get the corresponding value
ClearData (): Clears the data stored by the DataTransfer object
setdragimage (imageurl,log x,long y): Using an IMG element to set the drag-and-drop icon

Example:
Target.addeventlistener (' DragStart ', function (e) {
var fs = e.datatransfer.files;//gets drag-and-Drop File object list Flielist object
var dt=e.datatransfer;//as DataTransfer property for drag-and-drop events
dt.effectallowed= ' Copy ';
Dt.setdata (' Text/plain ', ' hello ');
Dt.setdragimage (DRAGICOM,-10,-10);
});

3. Drag and drop upload picture preview:

Ideas:
1. Familiar with the file drag and drop the target element of four events, note: OnDragOver, OnDrop event block default behavior
2. After dragging and dropping, get to the collection of file objects: E.datatransfer.files
3. Loops each file object in the collection, determines the file type and the file size, and then does the appropriate action for the specified type
4. Read the file Information object: New FileReader (), which has read the file object is Dataurl, and so on: Readasdataurl (File object), read after the success of the event triggered: OnLoad events, This.result to read the data
5. The corresponding logical processing in several events in the FileReader object

Html:

<div class= "Container" >
  <p class= "text" > Please drag the picture file to this area! </p>
</div>

Total load: <span id= ' Sum ' >100</span>

JQ:

<script type= "Text/javascript" > $ (function () {/* thread: *1. Familiar with file drag and drop target elements four events, note: OnDragOver, OnDrop event in the resistance Stop default behavior *2. Drag and drop to get to the collection of file objects: E.datatransfer.files *3. Loops each file object in the collection, determines the file type and the file size, and is the corresponding action *4 the specified type. Read the file Information object : New FileReader (), which reads the file object as Dataurl: Readasdataurl (File object), the event triggered after the read success: OnLoad event, etc., This.result for the read data *5.
      Logical handling of several events in a FileReader object *///must convert the JQ object to a JS object, invoke the native method var Odiv = $ (". Container"). Get (0);
      var OP = $ (". Text");
        Enter odiv.ondragenter = function () {op.html (");
        }//move, the default behavior needs to be blocked, otherwise the file Odiv.ondragover = function (e) {E.preventdefault () is displayed directly on this page. }//Leave Odiv.onleave = function () {op.html (' Please drag the picture file to this area!)
        ');
        //Drag drop, also need to block default behavior Odiv.ondrop = function (e) {e.preventdefault ();
        Get dragged over objects, file objects set var fs = E.datatransfer.files; If you select files for the file label in the form field, use the form[form Name].files[0] to obtainFetch file object set//Print length Console.log (fs.length);

          Loop multiple file drag upload for (var i = 0; i < fs.length i++) {//file type var _type = Fs[i].type;
          Console.log (_type);
            To determine the file type if (_type.indexof (' image ')!=-1) {//File size control Console.log (fs[i].size);
            Read the file object var reader = new FileReader ();
            Read as Dataurl, no return value Reader.readasdataurl (Fs[i]); Reader.onloadstart = function (e) {//Start loading}//This event is timed to trigger read while reading is in progress
            er.onprogress = function (e) {$ ("#total"). HTML (e.total);
                ///When read succeeds, This.result for read file data Reader.onload = function () {//File data
                Console.log (This.result);
                Add File preview var oimg = $ ("

Effect Chart:

Summary: combined with drag-and-drop event Api,datatransfer object and file reading object FileList and other aspects of knowledge, to achieve simple drag and drop upload picture preview effect. Need to know familiar with the relationship between the object and usage, clear to realize the idea!

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.