为了账号安全,请及时绑定邮箱和手机立即绑定

javascript如何上传blob?

javascript如何上传blob?

拉丁的传说 2019-11-15 15:10:15
javascript如何上传blob?我在这个结构中有一个blob数据:Blob {type: "audio/wav", size: 655404, slice: function}size: 655404type: "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);     });
查看完整描述

3 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

试试这个

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's processDatacontentTypeto false



查看完整回答
反对 回复 2019-11-16
?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

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

(仅在Chrome 28.0.1500.95中测试过)

// javascript function that uploads a blob to upload.phpfunction 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);?>



查看完整回答
反对 回复 2019-11-16
?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

实际上,您不必使用从JavaScript FormData发送Blob到服务器(File也是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});

Vanilla JavaScript示例:

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

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

来源:XMLHttpRequest2中的新技巧| HTML5 Rocks



查看完整回答
反对 回复 2019-11-16
  • 3 回答
  • 0 关注
  • 484 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信