javascript如何上传blob?

时间:2012-11-11 17:06:26

标签: javascript jquery html5

我在这个结构中有一个blob数据:

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

这实际上是使用最近的Chrome getUerMedia()Recorder.js

录制的声音数据

如何使用jquery的post方法将此blob上传到服务器?我没试过就试过这个:

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

5 个答案:

答案 0 :(得分:100)

试试这个

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);
});

您需要使用FormData API并将jQuery.ajax的{​​{1}}和processData设置为contentType

答案 1 :(得分:16)

我无法使用上面的示例来处理blob,我想知道upload.php到底是什么。所以你走了:

(仅在Chrome 28.0.1500.95中测试)

// javascript function that uploads a blob to upload.php
function uploadBlob(){
    // create a blob here for testing
    var blob = new Blob(["i am a blob"]);
    //var blob = yourAudioBlobCapturedFromWebAudioAPI;// for example   
    var reader = new FileReader();
    // this function is triggered once a call to readAsDataURL returns
    reader.onload = function(event){
        var fd = new FormData();
        fd.append('fname', 'test.txt');
        fd.append('data', event.target.result);
        $.ajax({
            type: 'POST',
            url: 'upload.php',
            data: fd,
            processData: false,
            contentType: false
        }).done(function(data) {
            // print the output from the upload.php script
            console.log(data);
        });
    };      
    // trigger the read from the reader...
    reader.readAsDataURL(blob);

}

upload.php的内容:

<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data, 
echo ($decodedData);
$filename = "test.txt";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>

答案 2 :(得分:11)

我能够通过不使用FormData但使用javascript对象传输blob来获得@yeeking示例。使用使用recorder.js创建的声音blob。已在Chrome版本32.0.1700.107中测试

function uploadAudio( blob ) {
  var reader = new FileReader();
  reader.onload = function(event){
    var fd = {};
    fd["fname"] = "test.wav";
    fd["data"] = event.target.result;
    $.ajax({
      type: 'POST',
      url: 'upload.php',
      data: fd,
      dataType: 'text'
    }).done(function(data) {
        console.log(data);
    });
  };
  reader.readAsDataURL(blob);
}

upload.php的内容

<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
$filename = $_POST['fname'];
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>

答案 3 :(得分:1)

我尝试了上面的所有解决方案,此外还有相关答案。解决方案包括但不限于手动将blob传递给HTMLInputElement的文件属性,调用FileReader上的所有readAs *方法,使用File实例作为FormData.append调用的第二个参数,尝试通过获取将blob数据作为字符串获取URL.createObjectURL(myBlob)中的值变得令人讨厌并使我的机器崩溃。

现在,如果你碰巧尝试那些或更多,但仍然发现你无法上传你的blob,这可能意味着问题是服务器端。在我的情况下,我的blob超出了PHP.INI中的http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize和post_max_size限制,因此文件离开了前端表单但被服务器拒绝了。您可以直接在PHP.INI中或通过.htaccess

增加此值

答案 4 :(得分:1)

2019更新

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

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

基本提取

它可能很简单:

  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代码

这是upload.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);
?>
相关问题