简体   繁体   English

从Blob网址下载数据

[英]Download data from blob url

I am creating an application that records audio from mic and gives an option to download it to the local drive. 我正在创建一个应用程序,该应用程序记录来自麦克风的音频,并提供了将其下载到本地驱动器的选项。 here is a piece of my code that generates an audio link with a timestamp. 这是我的一段代码,它生成带有时间戳的音频链接。

stopRecording(function(AudioBLOB){

                var url = URL.createObjectURL(AudioBLOB);
                var li = document.createElement('li');
                var au = document.createElement('audio');
                var hf = document.createElement('a');

                au.controls = true;
                au.src = url;
                hf.href = url;
                // Important:
                // Change the format of the file according to the mimetype

                hf.download = new Date().toISOString() + '.wav';
                hf.innerHTML = hf.download;
                li.appendChild(au);
                li.appendChild(hf);
                recordingslist.appendChild(li);
}, _AudioFormat);
            }, false);

How can I modify this code so instead of creating the link it would directly upload the file to my root folder. 如何修改此代码,而不是创建链接,而是直接将文件上传到我的根文件夹。

This sends the wav upstream, POST /upload, encoded as base64, along with metadata. 这会将wav上游,POST / upload(编码为base64)连同元数据一起发送。 The server will have to decode data and save it to the file-system: 服务器将必须解码data并将其保存到文件系统中:

class Audio {
    static createPayload(audioBlob) {
        return new Promise(function (resolve, reject) {
            const r = new FileReader();
            r.readAsDataURL(audioBlob);
            r.onloadend = function () {
                resolve(JSON.stringify({
                    filename: `${new Date().toISOString()}.wav`,
                    mimeType: 'audio/wav',
                    transferEncoding: 'base64',
                    data: r.result
                }));
            };
        });
    }
}

stopRecording(async function (audioBlob) {
    const payload = await Audio.createPayload(audioBlob);

    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload');
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(payload);
}, false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM