HTML5 file interface (using files on Web pages)

Source: Internet
Author: User

The file interface provides information about the files and runs JavaScript on the Web page to access the contents of the file.

The file object is derived from the FileList object returned by the user using the input tag selection file , from the DataTransfer object of the drag-and-drop operation . A file object is a special blob that can be used in any context in which a blob can be used.

To use a file in a Web page, you typically need to refer to the object: File object, FileList object, FileReader object.

FileList Object

FileList comes from two places, the files property of the input element, and the drag and drop API (event when you drag a file. Datatransfer.files is a FileList object)

<id= "Fileitem"  type= "file">

var fileList = document.getElementById (' Fileitem '). Files
standard properties for FileList objects

Length: This is a read-only property that returns the length of the file object contained in the FileList object.

standard methods for FileList objects

Item (Index): Gets the file object at the specified position in the FileList object. It can be abbreviated in the form of an array index

File Object

Each item of the FileList object is a file object. The file object is a special blob.

standard properties for file objects

1.lastModified: Returns the time the file was modified, which is the number of milliseconds elapsed from January 1, 1970 0 o'clock 0:0. is a read-only property

2.name: Returns the file name of the file referenced by the file object, which is a read-only property

3.type: Returns the file type of the file referenced by the file object, which is the mine type, which is a read-only property.

4.size: Returns the file size of the file referenced by the files object, which is a read-only property.

Standard methods for file objects

The method is not defined separately for the file object, but it has a method inherited from the Blob object.

FileReader Object

The FileReader object enables a web app to asynchronously read files on a user's computer.

FileReader () is a constructor that allows you to create a new FileReader object.

var New FileReader ();

standard properties for FileReader objects

1.error: Returns the error that occurred during file read.

2.result: Returns the contents of the file, and returns a string or Arraybuffer of the worthwhile type. This property is valid only after the read operation is complete.

3.readyState: Returns the current state of the read operation, the possible value is 0: has not started reading, 1: Reading, 2: Read complete.

standard methods for FileReader objects

1.abort (): Interrupt read operation. The value of readystate becomes 2.

2.readAsArrayBuffer (BLOB): reads the specified blob, such as a file object (the file object is a special blob). As soon as the read is complete, the value of the ReadyState property becomes the 2,result property is a arraybuffer that represents the file data.

3.readAsDataURL (BLOB): reads the specified blob, such as a file object (the file object is a special blob). As soon as the read is complete, the value of the ReadyState property becomes the 2,result property is a URL that represents the file data, and the data format is a base64 encoded string

 <  input  type  = "file"   onchange  = "Previewfile ()"  ><  BR  >  <  img  src  = ""   height  = ""  alt  = "Image preview ..."  >  
 function   Previewfile () { var  preview = document.queryselector (' img '  var  file = Document.queryselector (' input[type=file] '). Files[0);  var  reader = new   FileReader (); Reader.addeventlistener ( "Load", function    () {preview.src  = Reader.result;  },  false  );   if   (file) {reader.readasdataurl (file); }}

4.readAsText (boob,encoding): reads the specified blob, such as a file object (the file object is a special blob). As soon as the read is complete, the value of the ReadyState property becomes the 2,result property is a text string representing the file data. The second parameter is optional and is used to specify how the text string in the result property is encoded, by default, UTF-8.

Events for FileReader objects

1.abort: Triggered when a read operation is terminated.

2.error: Triggered when an error is encountered during a read operation.

3.load: Triggered when the read operation completes successfully.

4.loadend: Triggered at the end of the read operation. Cannot be a read success or a read failure.

5.loadStart: Triggered when the read operation starts.

6.process: Triggered during the read process.

Working with files in a web App

Using the file objects in HTML5, you can access the selected local files and read the contents of those files. The file object is either from the input element or from the drag and drop interface.

Selecting a file from the INPUT element
<type= "file"  ID= "input">

Accessing the file selected through input

var selectedfile = document.getElementById (' input '). Files[0];

The preceding code snippet can only select one file at a time, if you want to select multiple files at a time, you need to add a multiple property to the input element and set the multiple property to I true. Selecting more than one file at a time is not supported until Gecko 1.9.2.

selecting files via drag and drop interface

About the drag and drop interface you can view HTML5 dragevent.

First step: Create a drop zone. An ordinary element, such as div,p.

Step Two: Add the Drop,dragenter,dragover event handler to the drop zone. One of the key roles is the drop event handler.

Here is an example of a thumbnail display:

<IDclass= ' Dropbox '></Div  >
. Dropbox { Border:solid 3px Red; height:400px; width:auto;      }
varDropbox;dropbox= document.getElementById ("Dropbox");//Registering event HandlersDropbox.addeventlistener ("DragEnter", DragEnter,false);d Ropbox.addeventlistener ("DragOver", DragOver,false);d Ropbox.addeventlistener ("Drop", drop,false);functionDragEnter (e) {e.stoppropagation (); E.preventdefault ();}functionDragOver (e) {e.stoppropagation (); E.preventdefault ();}functionDrop (E) {e.stoppropagation ();  E.preventdefault (); varDT =E.datatransfer; varFiles =Dt.files; Handlefiles (files);}functionhandlefiles (files) { for(vari = 0; i < files.length; i++) {    varFile =Files[i]; varImageType =/^image\//; if(!imagetype.test (File.type)) {      Continue; }        varimg = document.createelement ("img"); Img.file=file; Dropbox.appendchild (IMG);         varReader =NewFileReader (); Reader.onload=function() {img.src=Reader.result;    };  Reader.readasdataurl (file); }}    

HTML5 file interface (using files on Web pages)

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.