jQuery 通过ajax传递Blob生成文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19015555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass Blob through ajax to generate a file
提问by Jo?o Correia
I'm trying to capture audiorecorder (https://github.com/cwilso/AudioRecorder) and send the blob through Ajax a php file, which will receive the blob content and create the file(the wave file in this case).
我正在尝试捕获 audiorecorder ( https://github.com/cwilso/AudioRecorder) 并通过 Ajax 向 blob 发送一个 php 文件,该文件将接收 blob 内容并创建文件(在本例中为波形文件)。
Ajax call:
阿贾克斯调用:
audioRecorder.exportWAV(function(blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var filename = <?php echo $filename;?>;
$.ajaxFileUpload({
url : "lib/vocal_render.php",
secureuri :false,
dataType : blob.type,
data: blob,
success: function(data, status) {
if(data.status != 'error')
alert("boa!");
}
});
});
and my php file (vocal_render.php):
和我的 php 文件(vocal_render.php):
<?php
if(!empty($_POST)){
$data = implode($_POST); //transforms the char array with the blob url to a string
$fname = "11" . ".wav";
$file = fopen("../ext/wav/testes/" .$fname, 'w');
fwrite($file, $data);
fclose($file);
}?>
P.S:I'm newbie with blobs and ajax. Thanks in advance.
PS:我是 blob 和 ajax 的新手。提前致谢。
回答by Musa
Try uploading the file as form data
尝试将文件上传为表单数据
audioRecorder.exportWAV(function(blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var filename = <?php echo $filename;?>;
var data = new FormData();
data.append('file', blob);
$.ajax({
url : "lib/vocal_render.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
alert("boa!");
},
error: function() {
alert("not so boa!");
}
});
});
.
.
<?php
if(isset($_FILES['file']) and !$_FILES['file']['error']){
$fname = "11" . ".wav";
move_uploaded_file($_FILES['file']['tmp_name'], "../ext/wav/testes/" . $fname);
}
?>
回答by juan.facorro
According to the documentation, by using XMLHttpRequest.send()
you can use the Blob
object directly.
根据文档,通过使用XMLHttpRequest.send()
您可以Blob
直接使用该对象。
var blob = new Blob(chunks, { 'type' : 'audio/webm' });
var xhr = new XMLHttpRequest();
xhr.open('POST', '/speech', true);
xhr.onload = function(e) {
console.log('Sent');
};
xhr.send(blob);
I've tried this and it works like a charm.
我试过这个,它就像一个魅力。