Examples of file operations using the HTML5 files API

Source: Internet
Author: User
Tags base64 file upload

It's written in front.

This period of time has been a friend to ask the file upload download, search the forum found that a number of related issues, but not enough system, in the spirit of serving the people this article tries to put some problems sorted out, for beginners can be more specific to deal with the relevant issues. File upload is the development of a snag, for a lot of people who have no experience, simply Meng, the current I know the way to upload there are the following:

Traditional Flash Upload

Hide IFrame Box upload

Form data Submission

HTML5 's new tool--file API

This article is limited to details about the last file upload using the HTML5 file API.

Historically, JavaScript cannot handle binary data. If you have to deal with it, you can only use the charCodeAt () method, one byte from the text encoding into binary data, there is another way is to convert the binary data into BASE64 encoding, and then processing. Both of these methods are slow and error prone. ECMAScript 5 introduces a Blob object that allows direct manipulation of binary data. A Blob object is a basic object representing binary data and, on the basis of it, derives a series of related APIs for manipulating files.

The File API

The file interface provides information about the files and how the contents of the file are accessed.

The file object can be used to retrieve information about a file, and it can be used to read the contents of it. Typically, a file object is a FileList object that is returned after a user selects a file on a <input> element, or it can be a DataTransfer object that is generated from a drag-and-drop operation.

Select files from the input file tag

The default input file label is ugly, need to transform themselves, is generally nothing more than the input file set wide, and then use the Overflow:hidden; the extra part is hidden, and the top is covered with a landscaping button or prompt, as shown below:


The code is as follows:

The code is as follows Copy Code
<! DOCTYPE html>
<meta charset= "UTF-8" >
<title></title>
<style type= "Text/css" >
*{
margin:0px;
padding:0px;
}
. filepicker{
width:160px;
height:44px;
line-height:44px;
Text-align:center;
Color: #fff;
Background: #00b7ee;
}
. filepicker input[type= "file" {
position:relative;
Top: -44px;
left:0px;
width:160px;
height:44px;
opacity:0;
Cursor:pointer;
Overflow:hidden;
z-index:0;
}

. container{
width:160px;
margin:30px Auto;
}
</style>
<body>
<div class= "Container" >
<input type= "File" name= "id=" "value=" "/>"
</div>
<div class= "Container" >
<div class= "Filepicker" >
<label> Click Select File </label>
<input id= "fileInput" type= "file" name= "file" multiple= "multiple" accept= "image/*" >
</div>
</div>
</body>

We can filter the file selection by setting the Accept property to the Input File tab, the value of which must be a comma-separated list containing multiple unique content type declarations:

The file name extension that starts with the STOP character (u+002e). (For example: ". Jpg,.png,.doc")

A valid MIME type, but no extension

audio/* represents an audio file HTML5

video/* represents a video file HTML5

image/* represents a picture file

Set the Multiple property to set whether it is a radio or a multiple selection.

With the file API, we can access one or more file objects that represent the selected file, after the user has selected either or more files, which are contained in a FileList object. All of the type attributes <input> elements of file have a files property that stores the file that the user chooses. Files have a length property and Item method that we can use Files[index] or Files.item (index) to get our selected file object. You can listen to the input file entry to complete the event through the Change event:

The code is as follows Copy Code
var fileInput = document.getElementById ("FileInput");
Fileinput.addeventlistener (' Change ', function (event) {
var file = Fileinput.files[0];
or file = FileInput.files.item (0);
Console.log (file);
}, False);

The file API provides a file object, which is a member of the FileList object, containing some meta information about the file, such as file name, last modified time, file size, and file type. The following figure can be a property of a file object:


LastModifiedDate: Date The File object was last modified

Name: file name, read-only string, does not contain any path information.

Size: File size, in bytes, read-only 64-bit integers.

Type:mime type, read-only String, and returns an empty string if the type is unknown.

For example: we can convert our customary file size expression by size:

  code is as follows copy code
/**
 * Read File size
 * @param {Object} file
 */
function readfilesize (file) {
    var size = fi le.size/1024;
    var amultiples = ["KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
   
    var filesizestring = ';
    for (var i = 0; size > 1 ; Size/= 1024, i++) {
       filesizestring = size.tofixed (2) + "" + amultiples[i];
   }
    return filesizestring
}

Sometimes we want to limit the size of the files uploaded by the user, so we can make a judgment first. At the same time we can judge the user's file type by the type attribute, but this method is unreliable because the user can implement it by changing the suffix name.

Many novice attempts to get the file full path through the input file tag, this is not allowed due to browser security, but sometimes we want to select the image to preview the picture, this time we can use the FileReader API implementation.

Selecting files by drag-and-drop operations

Preview Effect:


Code implementation:

The code is as follows Copy Code

<! DOCTYPE html>
<meta charset= "UTF-8" >
<title></title>
<style type= "Text/css" >
. dropbox{
width:300px;
height:300px;
margin:20px;
border:3px dashed #e6e6e6;
}
. area{
margin:100px Auto;
width:100px;
height:100px;
Background-repeat:no-repeat;
                Background-image:url ("Data:image/png;base64, Ivborw0kggoaaaansuheugaaafgaaablcaiaaab7tddwaaaagxrfwhrtb2z0d2fyzqbbzg9izsbjbwfnzvjlywr5ccllpaaaayrpvfh0we1momnvbs5hzg9iz s54bxaaaaaaadw/ehbhy2tldcbizwdpbj0i77u/iibpzd0ivzvnme1wq2voauh6cmvtek5uy3pryzlkij8+ Idx4onhtcg1ldgegeg1sbnm6ed0iywrvymu6bnm6bwv0ys8iihg6eg1wdgs9ikfkb2jlifhnucbdb3jliduumy1jmdexidy2lje0nty2mswgmjaxmi8wmi8wn I0xndo1njoynyagicagicagij4gphjkzjpsreygeg1sbnm6cmrmpsjodhrwoi8vd3d3lnczlm9yzy8xotk5lzaylziylxjkzi1zew50yxgtbnmjij4gphjkzj Pezxnjcmlwdglvbibyzgy6ywjvdxq9iiigeg1sbnm6eg1wpsjodhrwoi8vbnmuywrvymuuy29tl3hhcc8xljaviib4bwxuczp4bxbntt0iahr0cdovl25zlmf Kb2jllmnvbs94yxavms4wl21tlyigeg1sbnm6c3rszwy9imh0dha6ly9ucy5hzg9izs5jb20vegfwlzeumc9zvhlwzs9szxnvdxjjzvjlzimiihhtcdpdcmvh Dg9yvg9vbd0iqwrvymugughvdg9zag9wientniaotwfjaw50b3noksigeg1wtu06sw5zdgfuy2vjrd0ieg1wlmlpzdo1q0vbnza0mjeymduxmuuzodk2q0jfm 0q1rje4qkexqyigeg1wtu06rg9jdw1lbnrjrd0ieg1wlmrpzdo1q0vbnza0mzeymduxmuuzodk2q0jfm0q1rje4qkexqyi+ idx4bxbnttpezxjpdmvkrnjvbsbzdfjlzjppbnn0yw5jzulepsj4bxauawlkojaznda2mky1mtiwmzexrtm4otzdqkuzrdvgmthcqtfdiibzdfjlzjpkb2n1b wvudelepsj4bxauzglkojaznda2mky2mtiwmzexrtm4otzdqkuzrdvgmthcqtfdii8+idwvcmrmokrlc2nyaxb0aw9upia8l3jkzjpsrey+ idwvedp4bxbtzxrhpia8p3hwywnrzxqgzw5kpsjyij8+k6izdgaaavpjrefuenrsnfmpqkaqhwmx667gep9c/v+/mksdg+4lrvdcsygrbw/ 0alzq9wbujon+uqvqhgcg3e93hujruosaqbaiakegcasbibae4nericecii51xb/dbnjpgot0oqlukok7apn3jikwy6duibaegkaqcalho/ x47texy8u0tcuyrtdrzkps9/v2m8fginygf9qx/gtv+xw2dcnkbjkmxmkxsavc0kecdgfygq8cnp/pa5qwy+wihg6v13v7/ xpt6ha7al5d3hq1go1snkvtu8lkmsmtessocasbsfqew/ dq0tbr9w63o51okk6fqkfv1xq6nswq0ootyqsvjknzbdaa0mq1qcqafsffasxmm4ece1do0+luqrcsfggsphzq20ngsvqtkpiax+mxms+c/ axruvmxaonnd75j9w5huwwxuyavdrftg8epluphgjywqpafubd5dlhw/adwwgvtcdgcdzph1qisg+ dosvjkn44wyxjgc4xnvbunrtvt9gta2hv47sgszkvs4ef8edzg4vmvcrpsgeu3xpbzbdar1erll1aq7xabu8xaaxvb3xffbnihwkr2qcuyq9fr5xizoxktg6b Ekenlkdqf7awpfby1aoumu8rg/hme91nxm+j/orir07vclvf7fect+staqgibrnjtojoldahdj/hxgj5+u+tzikaf+mbkk00xfta2bhdrue0/9gv8elogbu4tbw8+ nyphhseuavqtvunqc6tzyqucxsg0tbfyaxfikogr9ynp1gjyyqz57qbg7auirfclkzwsldqwbqsmxm9zfalyh+ffbwjjskngqefxsrapw+ eq9qjew7is2sj8fgsw2nu1gylypkkrmsrta+4icja2fxsndkloq/ifacfp54up1yaqbijaeih4gwcpkhk+gj7aju/ficj+ qlighefodwqmtrjvylydrih4rsdt+bbm9tp5kuhrzn++e6sqqvcdyub/ sio6boegeascqbaiakegceqg8veaaqab1bbo2qoeewaaaabjru5erkjggg== ");
}

#preview img{
width:100px;
height:100px;
}
</style>
<body>
<div id= "Dropbox" class= "Dropbox" >
<div class= "Area" ></div>
</div>
<div id= "Preview" ></div>

<script type= "Text/javascript" >
var dropbox = document.getElementById ("Dropbox");
var preview = document.getElementById ("preview");

Dropbox.addeventlistener ("DragEnter", function (e) {
E.stoppropagation ();
E.preventdefault ();
}, False);

Dropbox.addeventlistener ("DragOver", function (e) {
E.stoppropagation ();
E.preventdefault ();
}, False);

Dropbox.addeventlistener ("Drop", function (e) {
E.stoppropagation ();
E.preventdefault ();

var dt = E.datatransfer;
var files = dt.files;

for (var i = 0; i < files.length; i++) {
var file = Files[i];
var imagetype =/^image\//;

if (!imagetype.test (File.type)) {
Continue
}

Fills the selected picture to the display area
var img = document.createelement ("img");
Img.classList.add ("obj");
Img.file = file;
Preview.appendchild (IMG);

Reading the contents of a File object
var reader = new FileReader ();
Reader.onload = (function (aimg) {
return function (e) {
AIMG.SRC = E.target.result;
};
) (IMG);
Reader.readasdataurl (file);
}
}, False);
</script>
</body>

In this example, the area of the element with the ID Dropbox is our drag-and-drop destination area. We need to bind dragenter,dragover, and drop events on this element. We must block the default behavior of the DragEnter and DragOver events in order to trigger the drop event. We get the DataTransfer object from the Drop event object, which contains the FileList object.

FileReader API

With the FileReader object, a Web application can asynchronously read the contents of a file (or raw data buffer) stored on a user's computer, and you can use a file object or a Blob object to specify the files or data that you want to work with. Where the file object can be from a user in a < The FileList object returned after selecting a file on the input> element can also come from a DataTransfer object that is generated by a drag-and-drop operation, or from a return result after the Mozgetasfile () method is executed on a htmlcanvaselement.

Datauri objects

In the above example of selecting files through drag-and-drop operations, we use the form of "data:image/png;base64,xxxxxxxxxxxxx" as a background rather than as a picture, which is also used in the selected picture display. This string, called the Datauri object, allows the encoding of a small file to be embedded in another document in the form of:

Data:[<mime type>][;charset=<charset>][;base64],<encoded data>
The whole can be regarded as three parts, namely declaration: Parameter + data, comma left is a variety of parameters, the right is the data.

URLs are abbreviations for Uniform Resource Locator, and each accessible resource in the web has a URL address, such as a picture, HTML file, JS file, and style sheet file that we can use to download this resource. In fact, the URL is a subset of the URI, which is the abbreviation for Uniform Resource Identifier. A URI is a protocol that is used to obtain resources, including their additional information. The additional information may be an address, or it may not be an address, and if it is an address, then the URI becomes a URL. Note that the data URI is not a URL because it does not contain the public address of the resource.

We can get through the FileReader Readasdataurl method:

The code is as follows Copy Code

var reader = new FileReader ();
Reader.onload = function () {
Console.log (This.result);
}
Reader.readasdataurl (file);
Sometimes we need to turn a Datauri object to a Blob object:

/**
* Datauri Turn blob
* @param {Object} Datauri
*/
function Datauritoblob (Datauri) {
var arr = datauri.split (', '), MIME = Arr[0].match (/:(. *?); [1];
return new Blob ([Atob (Arr[1])], {type:mime});
}

URL Object

We can also use the URL object in addition to embedding a file into another document, except that we can use the Base64 string as content Datauri. A URL object is used to generate a URL that points to a file object or Blob object.

Window. Url.createobjecturl

A static method creates a domstring whose URL represents an object in the parameter. The lifecycle of this URL and the document binding in the window in which it was created. The new URL object represents the specified File object or Blob object.

var objecturl = window. Url.createobjecturl (file);
Window. Url.revokeobjecturl

A static method is used to release a previous pass through the call window. An existing URL object created by Url.createobjecturl (). When you end up using a URL object, you should call this method to let the browser know that it is no longer necessary to maintain the reference to the file.

Window. Url.revokeobjecturl (Objecturl)
For example: Use an object URL to display a picture:

The code is as follows Copy Code

Window. URL = window. URL | | Window.webkiturl;

var img = document.createelement ("img");
img.src = window. Url.createobjecturl (BLOB);
Img.height = 60;
Img.onload = function (e) {
Window. Url.revokeobjecturl (THIS.SRC);
}
Document.body.appendChild (IMG);

FileReader API Detailed

State constants

EMPTY: The value is 0 and no data has been loaded;

LOADING: The value is 0, the data is being loaded;

Done: The value is 0 and all the read requests have been completed.

Property

Error: Errors that occurred while reading the file, read-only;

ReadyState: Indicates the current state of the FileReader object, the value being one of the States constants, read-only;

Result: The content of the file to be fetched, which is valid only after the read operation is complete, and the format of the data depends on which method the read operation originated, read-only.

Method

Abort (): Aborts the read operation. When returned, the value of the ReadyState property is done.

Readasarraybuffer (): Begins reading the contents of the specified Blob object or file object. When the read operation completes, the value of the ReadyState property becomes done and invoked if the Onloadend event handler is set. Also, the Result property contains a Arraybuffer object to represent the contents of the file being read.

Readasbinarystring (): Begins reading the contents of the specified Blob object or file object. When the read operation completes, the value of the ReadyState property becomes done and invoked if the Onloadend event handler is set. Also, the result property contains the original binary data for the file being read.

Readasdataurl (): Begins reading the contents of the specified Blob object or file object. When the read operation completes, the value of the ReadyState property becomes done and invoked if the Onloadend event handler is set. Also, the result property will contain a string in Data:url format to represent the contents of the file being read.

Readasdataurl (): Begins reading the contents of the specified Blob object or file object. When the read operation completes, the value of the ReadyState property becomes done and invoked if the Onloadend event handler is set. Also, the result property will contain a string in Data:url format to represent the contents of the file being read.

Readastext (): Begins reading the contents of the specified Blob object or file object. When the read operation completes, the value of the ReadyState property becomes done and invoked if the Onloadend event handler is set. Also, the result property will contain a string to represent the contents of the file being read.

Event handling

Onabort: Called when the read operation is aborted.

OnError: Called when there is an error in the read operation.

OnLoad: Called when the read operation completes successfully.

Onloadend: Called when the read operation completes, either successfully or unsuccessfully. The handler is invoked after onload or onerror.

Onloadstart: Called before the read operation will begin.

OnProgress: Periodic invocation during data reading.

Uploading an instance: uploading Files in binary streams

The code is as follows Copy Code
var fileInput = document.getElementById ("FileInput");
Fileinput.addeventlistener (' Change ', function (event) {
var file = Fileinput.files[0];
if (file) {
var reader = new FileReader ();
var xhr = new XMLHttpRequest ();
Xhr.onprogress=function (e) {
var percentage = Math.Round (e.loaded *)/e.total);
Console.log ("percentage:" +percentage);
}
Xhr.onload=function (e) {
Console.log ("percentage:100");
}
Xhr.open ("POST", "Fill in the server address here");
Reader.onload = function (evt) {
Xhr.send (Evt.target.result);
};
reader.readasbinarystring (file);
}
});

Blob binary Large Object

BLOB (Binary large object), binary large objects, is a container in which binary files can be stored.

There are several ways to create BLOB objects, you can call a blob constructor, you can also use the slice () method on an existing Blob object to cut out another Blob object, and you can call the Toblob method on the canvas object.

The first time to see the word is six months ago, at that time did not listen to a blob, and then the Internet to check, Balabala a lot of, at that time is not understood.

Looking at the previous series of APIs and objects, perhaps many students began to faint, but at the beginning of the Blob object, we have not mentioned, if this article does not mention, is obviously unreasonable. After all, as the file object of the dad, blob toiled. The above FileReader object can also manipulate BLOB objects.

A BLOB object has two read-only properties:

Size: The amount of binary data, in bytes.

Type: The MIME types of binary data, all lowercase, and an empty string if the type is unknown.

In AJAX operations, if the Xhr.responsetype is set to a blob, the binary data is received.

Blob constructors generate BLOB objects

A BLOB constructor that accepts two parameters. The first parameter is an array that contains the actual data, and the second parameter is the type of the data, neither of which is required. An array element can be any number of Arraybuffer,arraybufferview (typed array), Blob, or Domstring object.

For example:

The code is as follows Copy Code
var arr = [' var blob = new Blob (arr, {"type": "Text/xml"}); The Blob
Console.log (BLOB);

The effect is as follows:


Create the download file in the browser with JS

The front end of many projects, there is a need for file downloads, especially JS generated file content, and then let the browser perform download operations (such as online image editing, online code editing, IPRESST, etc.) but limited by the browser, in many cases we can only give a link, let the user click Open-"Save As." This link is as follows:

<a href= "File.js" >file.js</a>
When the user clicks on the link, the browser opens and displays the contents of the link to the file, which obviously does not fulfill our needs. HTML5 adds a download attribute to the a tag, as long as there is this property, the browser does not open the link to the file when clicked, but instead downloads (currently only Chrome, Firefox and opera support). Download will be directly using the name of the link as a file name, but can be changed, as long as the download add the desired file name, such as: download= "not-a-file.js." But this is not enough, the above method is only suitable for the case where the file is on the server. If the browser-side JS generated content, want to let the browser to download how to do it? Datauri can do this, but Datauri file types are limited and we can work around implementing blob objects.

The code is as follows Copy Code
<a "id=" ALink "> Download </a>
<script type=" text/javascript "
    function DownloadFile (EL, FileName, content) {
        var aLink = Document.queryselector (EL);
         var blob = new blob ([content]);                
        alink.download = FileName;
        alink.href = Url.createobjecturl (BLOB);
   }
    document.queryselector (' #aLink '). AddEventListener (' click ', Function () {
         downloadFile (' #aLink ', ' hello.txt ', '    })
</script>

The slice method of a Blob object generates a BLOB object

The slice method of a Blob object that blocks binary data by byte, returning a new Blob object.

The code is as follows Copy Code
var Newblob = Oldblob.slice (Startingbyte, endindbyte);

Here is an example of using a XMLHttpRequest object to split a large file into an upload.

The code is as follows Copy Code

function Upload (bloborfile) {
  var xhr = new XMLHttpRequest ();
  Xhr.open (' POST ', '/server ', true);
  X Hr.onload = function (e) {...};
  Xhr.send (bloborfile);
}

Document.queryselector (' input[type= ' file '] '). AddEventListener (' Change ', function (e) {
  var blob = this.files[0];

  CONST BYTES_PER_CHUNK = 1024 * 1024;//1MB CHUNK sizes.
  Const SIZE = blob.size;

  var start = 0;
  var end = Bytes_per_chunk;

  while (Start < SIZE) {
    upload (blob.slice (start));

    start = end;
    end = start + Bytes_per_chunk;
 }
}, False);

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.