美文网首页web前端
Blob和ArrayBuffer

Blob和ArrayBuffer

作者: 姜治宇 | 来源:发表于2022-08-24 11:40 被阅读0次
1.jpg
2.jpg
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <input type="file" class='preview' /> <br />

        <img class="img" style="width:200px;height:200px;" />

    </div>

    <div>
        <a class="down">下载文件</a>
    </div>
    <div>
        <input type="file" class='readfile' /> <br />
    </div>
    <div>
        分片上传:<input type="file" class='upload' /> <br />
    </div>
</body>

</html>
<script>
    //预览文件
    document.querySelector('.preview').addEventListener('change', e => {
        let file = e.target.files[0];
        console.log(file);
        let img = document.querySelector('.img');
        let imgUrl = window.URL.createObjectURL(file);
        img.src = imgUrl;
        img.onload = () => {
            window.URL.revokeObjectURL(imgUrl);
        }
    });
    //下载文件
    let downurl = './1.wav';
    fetch(downurl).then(response => response.arrayBuffer()).then((res) => {
        console.log('response', res);
        let blob = new Blob([res]);
        let url = window.URL.createObjectURL(blob);
        let a = document.querySelector('.down');
        a.download = 'music.wav';//下载的文件名
        a.href = url;//下载地址
    });

    //读取二进制流
    document.querySelector('.readfile').addEventListener('change', e => {
        let file = e.target.files[0];
        let reader = new FileReader();
        // reader.readAsText(file); //以文本形式读取
        // reader.readAsArrayBuffer(file);//以二进制流形式读取
        reader.readAsDataURL(file);//以base64形式读取
        reader.onload = () => {
            let content = reader.result;
            console.log('以base64读取》》》', content);
        }
    });
    //分片上传
    function upload(blob) {
        const formdata = new FormData();
        formdata.append('file',blob);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/upload');
       
        xhr.send(formdata);
    }
    document.querySelector('.upload').addEventListener('change', function (e) {
        var blob = this.files[0];
        const CHUNK_SIZE = 20;
        const SIZE = blob.size;
        var start = 0;
        var end = CHUNK_SIZE;
        while (start < SIZE) {
            upload(blob.slice(start, end));
            start = end;
            end = start + CHUNK_SIZE;
        }
    });
</script>

相关文章

网友评论

    本文标题:Blob和ArrayBuffer

    本文链接:https://www.haomeiwen.com/subject/fqkawrtx.html