我在这个结构中有一个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);
});
发布于 2012-11-12 01:17:29
您可以使用FormData API。
如果您使用的是jquery.ajax
,则需要设置processData: false
和contentType: 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);
});
发布于 2015-11-24 07:11:38
实际上,您不必使用FormData
从JavaScript向服务器发送Blob
( File
也是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 File
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload.php', true);
xhr.onload = function(e) { ... };
xhr.send(file);
当然,如果您要用"AJAX“实现替换传统的HTML multipart表单(即,您的后端使用多部分表单数据),那么您希望使用另一个答案中描述的FormData
对象。
发布于 2013-08-15 22:24:02
我不能让上面的例子与blobs一起工作,我想知道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);
?>
https://stackoverflow.com/questions/13333378
复制相似问题