123

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

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

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

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

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

6 回答 6

141

您可以使用FormData API

如果您使用jquery.ajax,则需要设置processData: 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);
});
于 2012-11-11T17:17:28.573 回答
45

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);
?>
于 2019-05-06T14:04:00.757 回答
22

您实际上不必使用从 JavaScript 向服务器FormData发送 a (并且 a也是 a )。BlobFileBlob

jQuery 示例:

var file = $('#fileInput').get(0).files.item(0); // instance of File
$.ajax({
  type: 'POST',
  url: 'upload.php',
  data: file,
  contentType: 'application/my-binary-type', // set accordingly
  processData: false
});

香草 JavaScript 示例:

var file = $('#fileInput').get(0).files.item(0); // instance of File
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload.php', true);
xhr.onload = function(e) { ... };
xhr.send(file);

当然,如果您要使用“AJAX”实现替换传统的 HTML 多部分表单(即,您的后端使用多部分表单数据),您希望使用FormData另一个答案中描述的对象。

来源:XMLHttpRequest2 中的新技巧 | HTML5 摇滚

于 2015-11-23T23:11:37.560 回答
19

我无法让上面的示例与 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);
?>
于 2013-08-15T14:24:01.747 回答
12

我能够通过不使用 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);
?>
于 2014-02-13T05:55:04.937 回答
2

我尝试了上述所有解决方案,此外还尝试了相关答案中的解决方案。解决方案包括但不限于手动将 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 增加此值

于 2017-10-17T05:37:47.877 回答