javascript如何上传blob?

IT技术 javascript jquery html
2021-01-10 13:10:23

我在这个结构中有一个 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);
    });
6个回答

您可以使用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);
});
@FullDecent 你是什么意思?提示用户使用 File API 下载文件?还是只存储 blob 内容?
2021-03-12 13:10:23
你知道如何在没有 AJAX 的情况下做到这一点吗?
2021-03-18 13:10:23
安全要求防止文件输入值的编程设置:stackoverflow.com/questions/1696877/...
2021-03-26 13:10:23
请注意,与文件不同,Blob 在发送到服务器时具有通用文件名。但是你可以在 FormData 中指定 Blob 文件名:stackoverflow.com/questions/6664967/...
2021-04-01 13:10:23
基本上要做 $('input[type=file]').value=blob
2021-04-07 13:10:23

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);
?>
最佳答案使用 jquery,甚至比这里的错误处理版本还要复杂。它有 126 票。另一方面,这有 11 票(现在 12 票)并且本机与 js 一起使用并且非常短。我希望我有 120 票可以把这个解决方案放在它所属的地方。
2021-03-29 13:10:23

您实际上不必使用从 JavaScriptFormData将 a 发送Blob到服务器(并且 aFile也是 a Blob)。

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 摇滚

我无法使用上面的示例来处理 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);
?>
我很确定您可以data: fd,ajax函数调用中的行更改data: blob,.
2021-03-15 13:10:23

通过不使用 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);
?>
在 php 文件中小心 - 如果您允许 HTTP 客户端设置文件名,他们可以使用它来将恶意内容上传到他们选择的文件和目录中。(只要Apache可以在那里写)
2021-03-22 13:10:23