我有以下功能:
Recorder.uploadAudio = function(blob, filename){
var reader = new FileReader();
reader.onload = function(event){
var data;
data = event.target.result;
$.post( "upload.php", { fname: filename, data: data } );
};
reader.readAsDataURL(blob);
$.get( "get_files.php", function( data ) {
$('#clips').html(data);
});
}
sript upload.php将文件保存到服务器,get_files.php刷新文件列表(它将所有音频文件加载到文件夹中并将其显示在列表中。)当我调试脚本时,upload.php不会t load,它在data = event.target.result
行停止。并且,blob参数加载正常,它代表了一个音频文件。
编辑:这是upload.php代码:
<?php
function is_dir_empty($dir) {
if (!is_readable($dir)) return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
function get_latest_index($path) {
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
$latest_index = preg_replace("/[^0-9]/","",$latest_filename);
$latest_index = (int)$latest_index;
$latest_index++;
if ($latest_index < "10") {
$latest_index = "0" . $latest_index;
}
return $latest_index;
}
// 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,
$path = "audio/";
$d = dir($path);
if (is_dir_empty($d)) {
$fname = "MyRecording00";
}
else{
$fname = "MyRecording" . get_latest_index($path);
}
$filename = "audio/" . $fname . ".wav";
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
答案 0 :(得分:0)
FileReader
onload
事件是异步的; $.post()
和$.get()
异步返回结果。尝试在$.get()
$.post()
事件中包括onload
和FileReader
;在$.get()
$.post()
var reader = new FileReader();
reader.onload = function(event){
var data;
data = event.target.result;
$.post( "upload.php", { fname: filename, data: data } )
.then(function() {
$.get( "get_files.php", function( data ) {
$('#clips').html(data);
})
});
};
reader.readAsDataURL(blob);