9
【笔记】JS 中的 File 和 Blob
source link: https://loli.fj.cn/2023/08/06/JS%E4%B8%AD%E7%9A%84File%E5%92%8CBlob/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
【笔记】JS 中的 File 和 Blob
2023-08-06
JS 中的 File 和 Blob
创建 File 对象
<text>
:文件内容<filename>
:文件名
var file = new File(["<text>", "<filename>"]);
获取字节数组
file.arrayBuffer();
var fileReader = new FileReader();
fileReader.onload = function(event) {
console.log(event.result);
}
fileReader.readArrayBuffer(file);
var fileReader = new FileReader();
fileReader.onload = function(event) {
console.log(event.target.result);
}
fileReader.readArrayBuffer(file);
创建 Blob 对象
<text>
:文件内容
var blob = new File(["<text>"]);
获取字节数组
blob.arrayBuffer();
获取字符串
blob.text();
修改字节数据
var dataView = new DataView(await blob.arrayBuffer());
根据字节地址查看字节
<index>
:字节地址
dataView.getUint8(<index>);
根据字节地址修改字节
<index>
:字节地址<value>
:修改后的字节值
dataView.setUint8(<index>, <value>);
通过浏览器获取文件
通过 input 标签
<input type="file" onchange="fun(event)">
<script>
const fun = function(event) {
console.log(event.target.files[0]);
}
</script>
<div style="width: 100px; height: 100px; background-color: red;" ondrop="fun1(event)" ondragover="fun2(event)"></div>
<script>
const fun1 = function(event) {
event.preventDefault();
console.log(event.dataTransfer.files[0]);
}
const fun2 = function(event) {
event.preventDefault();
}
</script>
通过 FilePicker
multiple
:是否允许上传多个
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK