In most cases, files are manipulated in the browser using a File object, retrieved from the element, and continued (such as displaying the selected image on the page, uploading the File to the server using Ajax, etc.). Here are the apis for manipulating files in a browser.
File objects inherit from Blob objects, so let’s look at Blob objects first.
1. A Blob object
A Blob object represents an immutable, raw data-like file object. Blobs don’t necessarily represent data in JavaScript’s native format.
Blob constructor Blob(array[, options])
- An array is an array of objects, such as An ArrayBuffer, an ArrayBufferView, a Blob, a String, or a mixture of similar objects, that will be put into the Blob. String will be encoded as UTF-8.
- Options is an optional object that may specify the following two properties:
- Type, which defaults to “”, represents the MIME type of the array content to be put into the BLOB.
- Hamed, whose default value is “transparent”, specifies how the string containing the line end \n is written. It is one of two values: “native”, which means that the line terminator is changed to a newline suitable for the host operating system file system, or “transparent”, which means that the end character saved in the BLOb is left unchanged.
Example:
var content1 = ['This is my firt trip to an island'];
var blob1 = new Blob(content, {type: 'text/plain'});
var content2 = {name: 'Alice'.age: 23};
var blob2 = new Blob([JSON.stringify(content2, null.2)] and {type: 'application/json'});
Copy the code
Blob instance properties
The attribute name | Read/write | describe |
---|---|---|
size | read-only | Blob The size (in bytes) of the data contained in the object. |
type | read-only | A string indicating the data contained in the Blob objectMIME type. If the type is unknown, the value is an empty string. Such as “image/PNG”. |
Example:
var content = ['<div id="box"><p class="pra">a paragraph</p></div>'];
var blob = new Blob(content, {type: 'text/html'});
console.log(blob.size); / / 50
console.log(blob.type); // text/html
Copy the code
Blob instance method
- slice([start[, end[, contentType]]])
The Slice method accepts three optional arguments, start and end, both numeric, indicating the interception range, and contentType specifying the MIME type of the intercepted content. Returns a new Blob object.
var blob = new Blob(['This is an example of Blob slice method'] and {type: 'text/plain'});
console.log(blob.size); / / 39
var newBlob = blob.slice(10.20.'text/plain');
console.log(newBlob.size); / / 10
Copy the code
To read content from a Blob object, use FileReader. This will be described below.
2. The File object
File constructor
Most of the operations we do with files are reads, and JS also provides a constructor for manually creating File objects: File(bits, name[, options]).
-
Bits (Required) ArrayBuffer, ArrayBufferView, Blob, or Array[String] – or any combination of these objects. This is the utF-8 encoded file contents.
-
Name [String] (Required) File name or file path.
-
Options [Object] (optional) Option Object, containing optional properties of the file. The options available are as follows:
type
: string indicates the content to be placed in the fileMIME
type. The default value is ”.lastModified
: A value representing the Unix timestamp in milliseconds when the file was last modified. The default is date.now ().
Example:
var file1 = new File(['text1'.'text2'].'test.txt', {type: 'text/plain'});
Copy the code
Create a File object from an existing blob object:
var file2 = new File([blob], 'test.png', {type: 'image/png'});
Copy the code
File instance attributes
The instance contents of the File object are not visible, but are accessible with the following properties:
The attribute name | Read/write | describe |
---|---|---|
name | read-only | Returns the name of the file. For security reasons, the returned value does not contain the file path. |
type | read-only | returnFile The media type (MIME) of the file represented by the. For example, a PNG image is “image/ PNG “. |
lastModified | read-only | Number, returns the number of milliseconds since 0:00, January 1, 1970, when the referenced file was last modified. |
lastModifiedDate | read-only | Date: returns the last modified Date of the current file. If the last modified Date of the file cannot be obtained, use the current Date instead. |
Example:
<input type="file" id='file'>
Copy the code
document.getElementById('file').addEventListener('change'.function(event){
const file = this.files[0];
if (file) {
console.log(file.name);
console.log(file.size);
console.log(file.lastModified);
console.log(file.lastModifiedDate); }});Copy the code
Note: Based on the current implementation, the browser does not actually read the byte stream of a file to determine its media type. It assumes file extensions; Rename the PNG image file suffix to.txt, and the type attribute value of the file read is “text/plain”, not “image/ PNG “. Also, file.type is only reliable for common file types. Examples are images, documents, audio, and video. Unusual file extensions return an empty string. Developers should not rely on this property as the only validation scheme.
File instance method
- slice([start[, end[, contentType]]])
The File object defines no additional methods, and since it inherits the Blob object, it also inherits the slice method, which is used in the same way as Blob’s slice method.
FileReader, url.createObjecturl (), createImageBitmap(), and xmlHttprequest.send () can all handle blobs and files.
3. FileReader object
The FileReader object allows a Web application to asynchronously read the contents of a File (or raw data buffer) stored on the user’s computer, using a File or Blob object to specify which File or data to read.
Where the File object can be a FileList returned by the user after selecting a File on an element, This can come from a drag-and-drop generated DataTransfer object, or it can come from executing mozGetAsFile() on an HTMLCanvasElement and returning the result.
FileReader constructor
var reader = new FileReader()
The constructor takes no arguments and returns an instance of FileReader. FileReader inherits the EventTarget object.
FileReader instance properties
The attribute name | Read/write | describe |
---|---|---|
error | read-only | DOMException Represents an error while reading a file. |
result | read-only | The contents of the file. This property is valid only after the load operation is completed. The format depends on the method of reading |
readyState | read-only | A number that represents the state of the file when it is read |
Note: The values of readeyState are as follows:
value | Constant names | describe |
---|---|---|
0 | EMPTY | No data has been loaded yet |
1 | LOADING | Data is being loaded |
2 | DONE | All read requests have been completed. |
Example:
var reader = new FileReader();
console.log(reader.error); // null
console.log(reader.result); // null
console.log(reader.readyState); / / 0
console.log(reader.EMPTY); / / 0
console.log(reader.LOADING); / / 1
console.log(reader.DONE); / / 2
Copy the code
EMPTY, LOADING, and DONE are properties that exist on both the FileReader and its prototype, so the instance has these properties, and the FileReader itself has these properties:
console.log(FileReader.EMPTY); / / 0
console.log(FileReader.LOADING); / / 1
console.log(FileReader.DONE); / / 2
Copy the code
FileReader event
Reading a file is an asynchronous process, and like an XMLHttpRequest object, a series of events are fired during the reading operation.
The name of the event | describe | Use the sample |
---|---|---|
abort | Triggered when the read operation is interrupted. | reader.onabort = function(event) {} |
error | Triggered when an error occurred in a read operation. | reader.onerror = function(event) {} |
load | Triggered when the read operation is complete. | reader.addEventListener('load', function(event) {}) |
loadstart | Triggered when the read operation starts. | reader.onloadstart = function(event) {} |
loadend | Triggered when the read operation ends (either successfully or failed). | reader.onloadend = function(event) {} |
progress | Triggered when a Blob is read. | reader.onprogress = function(event) {} |
FileReader instance method
Instances of FileReader have the following actionable methods:
Method names | describe | Use the sample |
---|---|---|
abort() | Manually terminate the read operation only whenreadyState When it is 1,readyState Value of 2 |
reader.abort() |
readAsArrayBuffer(blob) | Read the specifiedBlob 或 File Object. When the read operation is complete (triggeredloadend Event),result Property will contain oneArrayBuffer Object represents the data for the file read. |
reader.readAsArrayBuffer(blob) |
readAsDataURL(blob) | Read the specifiedBlob 或 File Object. When the read operation is complete (triggeredloadend Event),result Property will contain onedata:URL String format (Base64 encoded) |
reader.readAsArrayBuffer(file) |
readAsBinaryString(blob) | Obsolete, usedreadAsArrayBuffer Instead of |
— |
readAsText(blob[, encoding]) | Converts Blob or File objects to content (as strings) according to a special encoding. The default encoding isutf-8 |
reader.readAsArrayBuffer(blob) |
Example of reading a local picture:
<input type="file" id='file' accept="image/png, image/jpg, image/jpeg, image/gif" />><br />>
<img src="" alt="Image preview...">
Copy the code
var preview = document.querySelector('img');
var reader = new FileReader();
reader.addEventListener("load".function () {
preview.src = reader.result;
}, false);
document.getElementById('file').addEventListener('change'.function (event) {
var file = this.files[0];
if(file) { reader.readAsDataURL(file); }});Copy the code
Example of reading multiple files – CodePen
DataURL is a base64 encoded data format, and the display type is a string, such as data:image/ JPEG; base64,/9j/4QXERXhpZgAATU…
Convert dataURL to BLOB object:
function dataURLToBlob (dataurl) {
let arr = dataurl.split(', ');
let mime = arr[0].match(/ : (. *?) ; /) [1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
Copy the code
Create a File object from an existing object:
reader.addEventListener("load".function () {
preview.src = reader.result;
var blob = dataURLToBlob(reader.result);
var newFile = new File([blob], 'test.jpeg', {type: blob.type});
console.log(newFile.name); // test.jpeg
console.log(newFile.type);
console.log(newFile.size);
}, false);
Copy the code
URL.createObjectURL
Convert the image file to data:URL format for the element to display, using the url.createObjecturl method in addition to filereader.readasDataURL. The url.createObjecturl (blob) method returns a blob: string pointing to the file’s in-memory address.
<input type="file" id='file' accept="image/png, image/jpg, image/jpeg, image/gif" /><br />
<img src="" alt="Image preview...">
Copy the code
var preview = document.querySelector('img');
document.getElementById('file').addEventListener('change'.function (event) {
var file = this.files[0];
if(file) { preview.src = URL.createObjectURL(file); }});Copy the code
Comprehensive instance
Integrated above, can achieve a simple paste picture and display function. HTML5 provides content editing capabilities that allow you to paste part of an image, such as an image copied from a web page. However, images captured by the screenshot tool cannot be pasted and displayed, and images copied from the web page will have the original style and the image URL will also point to the original picture. We can use the following code to unify the two paste operations to achieve a uniform effect.
<div id="comment" contenteditable></div>
Copy the code
#comment{
border: 1px solid #ccc;
min-height: 500px;
padding: 10px;
}
#comment:focus {
border-color: #ccc;
outline: none;
}
.img-paste {
max-width: 100%;
}
Copy the code
var comment = document.getElementById('comment');
comment.addEventListener('paste'.function(event) {
console.log(event);
var item = event.clipboardData.files[0];
if (item && /image/.test(item.type)) {
var img = new Image();
img.src = URL.createObjectURL(item);
img.className = 'img-paste';
this.appendChild(img); event.preventDefault(); }},false);
Copy the code
Example effects can be viewed here.
Refer to the link
- using files from web apps – MDN
- Blob – MDN
- MIME types – Wikipedia
- MIME TYPES – MDN
- FileReader – MDN
- MIME types – w3school
- Blob/DataURL/canvas/image transformation