Introduction to HTML5 's file-related API usage

Source: Internet
Author: User
Tags file upload html form strlen

A. File and blob

A Blob object is a class file object that contains read-only raw data. The data in a BLOB object does not necessarily have to be a native form in JavaScript. The file interface is based on a blob, inherits the functionality of the Blob, and extends support for local files on the user's computer.

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 above is an explanation of the official tone of the MDN. In fact, a blob is one of the general terms in the computer World: a BLOB (binary large object) that represents a binary large object. In the Mysql/oracle database, there is a BLOB type that stores binary data specifically.

1.1 Blob constructor

Blob blob (
[Optional] Array parts,
[Optional] Blobpropertybag Properties
)
Parts

An array that contains the data that will be added to the Blob object. An array element can be any number of Arraybuffer, Arraybufferview (typed array), Blob, or Domstring object.

Properties

An object that sets some of the properties of a Blob object

For example, the following code can create an XML-formatted data:

var afileparts = [' <a id= ' a ' ><b id= ' B ' >hey!</b></a> '];
var omyblob = new Blob (afileparts, {"type": "Text/xml"}); The Blob

1.2 Canvas.toblob method

The Htmlcanvaselement.toblob () method creates a Blob object to display the picture on the canvas, which can be cached or saved locally and determined by the user's proxy. If not specifically, the type of the picture defaults to Image/png, with a resolution of 96dpi.

Using Canvas.toblob, you can convert a canvas image to a file, and the following code:

var canvas = document.getElementById ("Canvas");
Canvas.toblob (function (BLOB) {
var newimg = document.createelement ("img"),
url = url.createobjecturl (BLOB);
Newimg.onload = function () {
No longer need to read the Blob so it ' s revoked
Url.revokeobjecturl (URL);
};
newimg.src = URL;
Document.body.appendChild (NEWIMG);
});

1.3 Xmlhttprequest.responsetype = Blob

The Xmlhttprequest.responsetype = Blob is set in XMLHttpRequest2.0, and Xmlhttprequest.response is a BLOB object when the response is received.

function Readbloburl (SRC, callback) {
var xhr = new XMLHttpRequest ();
var blob;
Xhr.open ("Get", SRC, true);
Xhr.responsetype = ' blob ';
Xhr.onload = function (e) {
if (E.target.status = 200)
Return callback (E.target.response); E.target.response is the return of the request is a BLOB object
}
Xhr.send ();
return blob;
}
For example, in a project I need to play the. Amr and. SPX audio files on the server, HTML5 's audio tag is not supported in both formats. Sorting out the idea, there is a special JS library can decode AMR or SPX files for the original audio data, and then use Audiocontext API to play the original audio data. However, the parameters of the decoding function are arraybuffer or binarystring format audio data, so the audio file should be made into Arraybuffer or binarystring. Just FileReader can read a Blob object as first Arraybuffer and binarystring.

Thump thump, Xmlhttprequest.responsetype = BLOB sparkle debut!!! Download the audio file directly from the server as a Blob object. Perfect solution to the demand, you can go home with your girlfriend ~ ~

1.4 File

File inherits from a Blob object, so it is essentially a class file object that reads only raw data. However, the file object has more name, size, type, lastmodified properties.

<input type= "File" id= "Harrywan" >
<script>
document.getElementById (' Harrywan '). AddEventListener (' Change ', function (evt) {
var file = Evt.target.files[0];
Console.log (file)
}, False);
</script>

The following figure is the result of the console printing after you select a picture:


The image above can clearly see the name, size, type property. The constructor of the file object is that the File,file object inherits from the Blob.

Two. FileReader

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 Blob object to specify the files or data that you want to work with.

FileReader has five methods:

void Abort ();
Begins to read 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.
void Readasarraybuffer (in blob blob);
The result property will contain the original binary data for the file being read.
void Readasbinarystring (in blob blob);
The result property will contain a string in Data:url format to represent the contents of the file being read.
void Readasdataurl (in blob blob);
The result property contains a string to represent the contents of the file being read.
void Readastext (in blob blob, [optional] in domstring encoding);
Readasarraybuffer returns the Arraybuffer, Readasbinarystring returns a binary string, which can be converted by the following method:

function Ab2str (BUF) {
return String.fromCharCode.apply (NULL, New Uint16array (BUF));
}

function Str2ab (str) {
var buf = new Arraybuffer (str.length*2); 2 bytes for each char
var bufview = new Uint16array (BUF);
For (Var i=0, strlen=str.length i<strlen; i++) {
Bufview[i] = str.charcodeat (i);
}
return buf;
}
Binarystring are assembled into a data specification string by WINDOW.BTOA () encryption.

Readasdataurl can be a very convenient implementation of the picture preview:

Suppose file is a file object
var image = new Image ();
var file = E.target.files[0];
var filereader = new FileReader ();
Filereader.onload = function (ofrevent) {
var data = OFREvent.target.result; Data is the base64 of the code.
IMAGE.SRC = data;
};
Filereader.readasdataurl (file);

Three. FormData

XMLHttpRequest Level 2 Adds a new interface formdata. Using the Formdata object, we can simulate a series of form controls using JavaScript with some key-value pairs, and we can also use the XMLHttpRequest send () method to commit the "form" asynchronously. The great advantage of using formdata is that we can upload a binary file asynchronously compared to ordinary Ajax.

2.1 Formdata Constructor

New FormData (form?: htmlformelement)
form (optional): An HTML form element that can contain any form control, including a file input box.

2.2 Append ()

void Append (domstring name, Blob value, optional domstring filename);
void Append (domstring name, domstring value);
Adds a key/value pair to the current Formdata object, and the value can be blob and domstring.

2.3 Uploading files

The following are examples of using formdata:

var omyform = new FormData ();

Omyform.append ("username", "Groucho");
Omyform.append ("AccountNum", 123456); The number 123456 is immediately converted to the string "123456"

The files selected by the user are already included in the Fileinputelement
Omyform.append ("UserFile", Fileinputelement.files[0]);

var ofilebody = ' <a id= ' a ' ><b id= ' b ' >hey!</b></a> '; The contents of the file contained in a BLOB object
var oblob = new Blob ([Ofilebody], {type: "Text/xml"});

Omyform.append ("Webmasterfile", Oblob);

var oreq = new XMLHttpRequest ();
Oreq.open ("POST", "http://foo.com/submitform.php");
Oreq.send (Omyform);
Give me the feeling to use formdata like we submit form forms, and still asynchronous! With Formdata, there's no need to forge a hidden form to implement file uploads. Ajax default Content-type is application/x-www-form-urlencoded, after using Formdata, Content-type is multipart/form-data.

With Formdata can be very simple to achieve file upload. And Formdata compatibility is also good:


2.4 Fake Upload button


Since cooperating with the designer, select the file is either designed as an icon, or a button style, Meimei. Previously, I will place a hidden input, and then use Control div cover input, click Div, the equivalent of clicking on the input trigger file selection effect. But the effect is not very good, click on the domain and the effect of the gesture unfriendly.

Starting with Gecko 2.0 (Firefox 4/thunderbird 3.3/seamonkey 2.1), you can hide the default file entry box <input> elements and use a custom interface to act as a button to open the File selection dialog box. It's simple to implement, you just need to use style display:none to hide the original file input box, and then call its click () method when needed.

Consider the following HTML:

<input type= "file" id= "Fileelem" multiple accept= "image/*" style= "Display:none" onchange= "Handlefiles" ( This.files) "
<a href=" # "id=" Fileselect ">select some files</a>
var fileselect = document.getElementById ("Fileselect"),
  Fileelem = document.getElementById ("Fileelem");
Fileselect.addeventlistener ("click", Function (e) {
  if (fileelem) {
    fileelem.click ();
 }
  E.preventdefault ();
}, False);
This way, you can change the style of the file selection button arbitrarily. Designer, come on, do whatever you want.

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.