Article Directory
relation
introduce
Blob
-
introduce
- is an immutable, raw data file-like object
- is essentially an object of js
- size: the size of the contained data (bytes)
MIME
type: the type of data contained
- It stores binary data
FileReader
The contents of the blob can be read using
-
create
// 语法 const blob = new Blob(array, options); // 示例 const blob = new Blob([JSON.stringify(debug, null, 2)], { type : 'application/json'}); const myBlob = new Blob([1,2,3],{ type:'text/plain'}); console.log(myBlob);//Blob {size: 3, type: "text/plain"} console.log(myBlob.size);//3 console.log(myBlob.type);//'text/plain'
File
-
introduce
File
object is specialBlob
- Instantiation has 3 parameters:
new File(array, name, options)
- Generally, the File object is obtained by uploading
- By
input type=file
selecting the file, returnfileList
the object - Drag and drop files to generate
DataTransfer
objects
- By
-
create
const file = new File([file], file.name, { type: file.type}); // input上传 <input type="file" id="file"> <script> let obj = document.querySelector('#file') obj.addEventListener('change', (event) => { console.log(event.target.files[0]); }) </script> // 拖拽 <div class="drop" style="background-color: pink; height: 50px;"></div> <script> let obj = document.querySelector('.drop') obj.ondragover = e => { e.preventDefault()} obj.ondrop = e => { e.preventDefault() console.log(e.dataTransfer.files); } </script>
FileReader
It is a built-in method of js, which helps to realize File/Blob
the content of the object read
readAsArrayBuffer(file) 异步按字节读取文件内容,完成之后,result属性中保存被读文件的ArrayBuffer数据对象。
readAsBinaryString(file): 异步按字节读取文件内容,结果为文件的二进制串
readAsDataURL(file) 异步读取文件内容,结果用data:url的字符串形式表示。
readAsText(file) 异步按字符读取文件内容,result中包含的是字符串。
onabort 当读取操作被中止时调用
onerror 当读取操作发生错误时调用
onload 当读取操作成功完成时调用
onloadend 当读取操作完成时调用,不管是成功还是失败
onloadstart 当读取操作将要开始之前调用
onprogress 在读取数据过程中周期性调用
binary array
ArrayBuffer对象
,TypedArray视图
andDataView视图
is an interface for JavaScript to manipulate binary data- They are all
以数组的语法处理二进制数据
, so collectively referred to as binary arrays - Binary arrays are not really arrays, but
类似数组的对象
It consists of three types of objects
-
ArrayBuffer对象
Represents a piece of binary data in memory, which can be manipulated through "view". The "view" implements the array interface, which means that the memory can be manipulated with the methods of the array.
-
TypedArray视图
Including 9 types of views, such as Uint8Array (unsigned 8-bit integer) array view, Int16Array (16-bit integer) array view, Float32Array (32-bit floating point number) array view and so on.
-
DataView视图
You can customize the composite format view, for example, the first byte is Uint8 (unsigned 8-bit integer), the second and third bytes are Int16 (16-bit integer), and the fourth byte is Float32 (32-bit integer) Floating-point numbers), etc., and you can also customize the endianness.
ArrayBuffer object
ArrayBuffer cannot directly read the stored content, it needs to use TypedArray
objects or DataView
objects to read and write
URL.createObjectURL
- A URL pointing to the parameter object will be created based on the incoming parameters
- The life cycle of this URL exists in the document it was created in
- Generally, you can preview binary data such as pictures, audio, and video in the browser without uploading to the server
usage
<!DOCTYPE html>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<input type="file" name="imgFile" id="imgFile" onchange="changeFile()" />
<br />
<img id="previewImg" src="" alt="Preview Image" />
<script>
function changeFile() {
const imgFile = document.getElementById('imgFile').files[0]; // 接口需要的参数 file类型的图片
console.log(imgFile.size);
if (imgFile.size > 1024 * 1024 * 2) return alert('不允许超过 2 M');
const typeArr = ['image/png', 'image/jpeg', 'image/git', 'image/jpg'];
if (!typeArr.includes(imgFile.type)) return alert('只支持jpg,png,jpeg,gif格式');
// 生成预览图片地址:通过js将文件信息在本地电脑内存中变成一个预览地址临时拿去使用显示
const imgUrl = URL.createObjectURL(imgFile);
console.log(imgUrl); // blob:null/a0972036-a4b0-4821-9a0e-b2003797cb3d
document.getElementById('previewImg').src = imgUrl;
}
</script>
</body>
</html>
base64
-
introduce
- Is a representation method based on 64 printable characters to represent binary data
- Applications that need to store and transmit binary data through uploads designed to
文本数据
encode媒介
-
Conversion method (js)
atob()
:decodingbtoa()
:coding
-
Practical application scenarios
-
Convert canvas to base64 encoded format picture
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext("2d"); const dataUrl = canvas.toDataURL();
-
Convert pictures, files, etc. to base64 for transmission or storage
-
convert
file to base64
export const FileToBase64 = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
resolve(e.target.result);
};
reader.onerror = () => {
reject();
};
reader.readAsDataURL(file);
});
};
blob to base64
export const blobToBase64 = (blob) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
resolve(e.target.result);
};
reader.onerror = () => {
reject();
};
reader.readAsDataURL(blob);
});
};
base64 to blob
export const base64ToBlob = (code) => {
const parts = code.split(";base64,");
const contentType = parts[0].split(":")[1];
const raw = window.atob(parts[1]);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
"type": contentType
});
};
baes64 to file
export const base64ToFile = (code, fileName) => {
const parts = code.split(";base64,");
const contentType = parts[0].split(":")[1];
const fileExt = contentType.split("/")[1];
const raw = window.atob(parts[1]);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new File([uInt8Array], `${
fileName }.${
fileExt }`, {
"type": contentType
});
};
blob to file
export const blobToArrayBuffer = (blob) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
resolve(e.target.result);
};
reader.onerror = () => {
reject();
};
reader.readAsArrayBuffer(blob);
});
};
blob to ArrayBuffer
export const blobToArrayBuffer = (blob) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
resolve(e.target.result);
};
reader.onerror = () => {
reject();
};
reader.readAsArrayBuffer(blob);
});
};
file to ArrayBuffer
export const fileToArrayBuffer = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
resolve(e.target.result);
};
reader.onerror = () => {
reject();
};
reader.readAsArrayBuffer(file);
});
};