JavaScript如何上传一个blob?

2022-08-30 04:36:34

我有一个此结构中的 blob 数据:

Blob {type: "audio/wav", size: 655404, slice: function}
size: 655404
type: "audio/wav"
__proto__: Blob

它实际上是使用最近的Chrome和Recorder录制的声音数据.jsgetUerMedia()

如何使用jquery的post方法将此blob上传到服务器?我尝试过这个,没有任何运气:

   $.post('http://localhost/upload.php', { fname: "test.wav", data: soundBlob }, 
    function(responseText) {
           console.log(responseText);
    });

答案 1

您可以使用 FormData API

如果使用的是 ,则需要设置 和 。jquery.ajaxprocessData: falsecontentType: false

var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('data', soundBlob);
$.ajax({
    type: 'POST',
    url: '/upload.php',
    data: fd,
    processData: false,
    contentType: false
}).done(function(data) {
       console.log(data);
});

答案 2

2019年更新

这使用最新的Fetch API更新答案,不需要jQuery。

免责声明:不适用于IE,Opera Mini和较旧的浏览器。见卡纽斯

基本抓取

它可以像这样简单:

  fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
                .then(response => console.log(response.text()))

使用错误处理进行抓取

添加错误处理后,它可能看起来像这样:

fetch(`https://example.com/upload.php`, {method:"POST", body:blobData})
            .then(response => {
                if (response.ok) return response;
                else throw Error(`Server returned ${response.status}: ${response.statusText}`)
            })
            .then(response => console.log(response.text()))
            .catch(err => {
                alert(err);
            });

网络工序代码

这是上载中的服务器端代码.php。

<?php    
    // gets entire POST body
    $data = file_get_contents('php://input');
    // write the data out to the file
    $fp = fopen("path/to/file", "wb");

    fwrite($fp, $data);
    fclose($fp);
?>