js files in the file

In the web often need to deal with files, this comb.

1, file
file (File) interface provides information about the file, and allows access to its web page in JavaScript content.

Typically, the user File objects from a <input> select the file returned FileList element on the object (<input type = "file" > element attributes files), it may be free to drag and drop objects DataTransfer generated by the operation the files, or from the upper HTMLCanvasElement the mozGetAsFile () API.
File object is a special type of Blob, and may be used in any type of Blob context. For example, FileReader, URL.createObjectURL (), createImageBitmap (), and XMLHttpRequest.send () File Blob and can handle
constructors: File ()
        var = myFile new new File (bits, name [, Options]);
        bits: ArrayBuffer, ArrayBufferView, Blob, or Array DOMString objects - or a combination of any of these objects. This is UTF-8 encoded content files.
        name: represents a file name or file path
        options: Optional object properties. Contains type and lastModified, type: DOMString, said it would be put MIME type of the contents of the file. The default is "." lastModified: value indicates the time of last modification Unix timestamp (in milliseconds). The default is Date. now ().

Properties: inherits the properties of the Blob interface
        File.lastModified: Returns the File object references a file was last modified, the number of milliseconds since the UNIX time starting value (January 1 1970 00:00:00 UTC) is. Read-only
        File.lastModifiedDate: Returns the File object file was last modified Date object referenced. Read-only
        File.name: File object returns the current name of the file being referenced. Read-only
        File.size: Returns the size of the file. Read-only
        File.webkitRelativePath: File returns associated path or URL. Read-only
        File.type: Returns the file type Multipurpose Internet Mail Extensions (MIME Type). Read-Only
File interface does not define any method, but the following methods inherited from the interface Blob:
        Blob.slice ([Start [, End [, contentType]]]): Returns a new Blob object, which contains an active object Blob the data in the specified range.
                start: Representative Blob in the subscript denotes the first one will be will be copied into the new position of the starting byte of the Blob, and if it is negative, then the offset will start from the end data from back to front calculated, its default value is 0, if you pass a length greater than the length of the source start Blob, the return will be a length of 0 and does not contain any data of a Blob object
                end: it will be copied into the last byte position of the new Blob, if negative, then the offset will be calculated from the end of the data from back to front. Default is its original length (size).
                contentType: to the new Blob gives a new document type. This will put its type attribute set to be passed in value. Its default value is a null string

2, Blob
Blob object represents an immutable data object from the original class file. JavaScript is not necessarily the data in its native format Blob represented. File-based interface Blob, blob inherited and extended functionality to support files on the user's system.
Constructor: Blob (), new new Blob (Array, Options)
        Array: the Array is a, or a mixture of other similar objects made of ArrayBuffer, ArrayBufferView, Blob, DOMString and other objects, which will be kept on Blob.
        options is an optional BlobPropertyBag dictionary might specify the following two properties, type and endings, type, default value is "", which represents the MIME type endings will be put to the contents of the array blob of default values is "transparent", for specifying a line terminator comprising \ n how the string is written. It is one of two values: "native", on behalf of line endings will be changed to fit the host operating system, file system, line breaks, or "transparent", on behalf of the blob will remain stored in the same endings

property and method
Blob.size: data size (in bytes) contained Blob object. Read-only
Blob.type: a string indicating the MIME type of the data comprising the Blob object. If the type is unknown, the value is an empty string. Read-only
Blob.slice ([start, [end, [contentType]]]): Returns a new Blob object containing the data source Blob object in the specified range.

. 3, the FileReader
the FileReader object allows a Web application asynchronous read files stored on the user's computer (or raw data buffers) content, using the File or Blob object file or specify the data to be read.
Constructor: new FileReader ()
Attribute:
        FileReader.error, a DOMException, an error occurred when reading the file. Read-only
        FileReader.readyState: number representing FileReader state. Values are as follows: 0 (EMPTY, any data has not been loaded), 1 (LOADING, data is being loaded), 2 (DONE, has completed all of the read request). Read-only
        FileReader.result: the contents of the file. This attribute is only valid after the read operation is completed, the data format depends on which method to use to start the read operation. Read-only
event handler:
        FileReader.onabort: processing abort event. This event is triggered when a read operation is interrupted
        FileReader.onerror: processing error event. This event is triggered when a read operation error occurs
        FileReader.onload: processing load event. This event is triggered when the read operation is completed
        FileReader.onloadstart: processing loadstart event. This event is triggered when the reading operation starts
        FileReader.onloadend: processing loadend event. The event (either succeed or fail) at the end of the read operation trigger
        FileReader.onprogress: processing progress event. The event triggered when reading Blob
        because FileReader inherited from EventTarget, so all of these events can also be used by addEventListener method.

Method:
        FileReader.abort (): abort the read operation. In return, readyState property is DONE. For a read operation is not in progress (readyState not LOADING) of FileReader be abort the operation, it will throw DOM_FILE_ABORT_ERR error.
        FileReader.readAsArrayBuffer (blob | file): used to start reading the contents of the specified Blob or File. When the read operation is completed, the readyState into the DONE (completed), and trigger event loadend, while in the attribute contains a result ArrayBuffer object to represent the data file is read.
        FileReader.readAsBinaryString (blob | file): read the specified Blob or File object, when the reading is completed when, readyState becomes DONE (completed), and trigger loadend event, while the result property will contain the original file read binary format. From July 12, 2012, which abolished from the W3C Working Draft.
        FileReader.readAsDataURL (blob | file): read the specified Blob or File object. Read operation is complete when, readyState has been completed will become DONE, and trigger loadend event, while the result property will contain a data: string (base64 encoded) URL format to represent the contents of the file read.
        FileReader.readAsText (blob | file [, encoding ]): or a File object Blob may be transformed according to a particular coding format content (string), the second parameter is a string type of encoding, such as the default, default It is "utf-8" type.
This method is asynchronous, meaning only after the execution is complete to be able to view the results, if the direct view is inconclusive, and returns undefined. Onload must mount or onloadend example of a method of treatment. When the conversion is complete, this parameter will be converted to the readyState done complete state, event ( "loadend, load" ) mounted event is triggered, result in the attribute contains a string that represents the contents of the file to read, in the event parameters can also be event.target.result event handler in the

URL
        URL.createObjectURL (File | Blob | MediaSource) static method creates a DOMString, which contains a URL object parameters given representation (you can specify img , iframe src attribute). The URL of the life cycle and create its window document binding. The new URL File object represents an object or Blob object specified.
        URL.revokeObjectURL (objectURL);
Each call createObjectURL () method will create a new URL object, even if you've been with the same objects created as a parameter. When these URL object is no longer needed, each object must call URL.revokeObjectURL () method to release. The browser will automatically release them when the document exit.



https://developer.mozilla.org/zh-CN/docs/Web/API/File/Using_files_from_web_applications

  var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // 一个包含DOMString的数组
    var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // 得到 blob

    // 使用 Blob 创建一个指向类型化数组的URL
    var typedArray = GetTheTypedArraySomehow();
    var blob = new Blob([typedArray], {type: "application/octet-binary"});// 传入一个合适的MIME类型
    var url = URL.createObjectURL(blob);// 会产生一个类似blob:d3958f5c-0777-0845-9dcf-2cb28783acaf 这样的URL字符串,你可以像使用一个普通URL那样使用它,比如用在img.src上。

    //从 Blob 中提取数据,从Blob中读取内容的唯一方法是使用 FileReader
    // 一个文件上传的回调 <input type="file" onchange="onChange(event)">
    function onChange(event) {
        var file = event.target.files[0];
        var reader = new FileReader();
        reader.onload = function(event) {
            // 文件里的文本会在这里被打印出来
            console.log(event.target.result)
        };

        reader.readAsText(file);
    }

    var file = new File(["foo"], "foo.txt", {
        type: "text/plain",
    });
    console.log(file);

 



Guess you like

Origin www.cnblogs.com/zhanglw456/p/11270617.html