怎么样...
我们必须假设有某种方法可以确定总作业 (100%) 和 php 脚本所处的点(完成百分比),所以如果它正在读取/解析文本文件,你可以解析函数首先将总行数写入数据库或文本文件。然后它还可以每 5 秒将它所在的行号写入同一个文件。 js ajax 函数调用该文本文件以获取总数和它所在的点。 php文本解析器完成后,会销毁状态文件,防止占用服务器空间、文件名冲突等。
例子:
首先,(jquery) ajax 函数 POST 到服务器:
$.post("parser.php", { file: "somefile.txt"} );
//I admit, I'm not sure if this is how a file would be posted with ajax
接下来,php拉取文件并启动解析器功能:
$tmpName = $_FILES['userfile']['tmp_name'];
$fileName = $_FILES['userfile']['name'];
//Turn the file into an array, so that you can use the array count for status:
$content = file($tmpName);
// Get the array count as the total, as it equals the line count:
$total = count($content);
//Write the filesize to a unique "total" txt file:
$total_file = fopen($fileName."-total.txt", 'x');
fwrite($total_file, $total);
fclose($total_file);
//Pass the Array to the parser function:
parser($content, $fileName);
//Kill the file when the function is done:
unlink($fileName);
function parser ($file_array, $filename) {
//creates the status file and then closes it, to ensure that it
//exists for the loop but gets overwritten each time
$status_file = fopen($filename."-status.txt", 'x');
fclose($status_file);
foreach($file_array as $position => $data) {
//Do your parsing here //
.............
//reopen status file and wipe out what is in it already:
$status_file = fopen($filename."-status.txt", 'w');
fwrite($status_file, $position);
fclose($status_file);
}
}
因此,由于状态和总文件共享希望上传文件的唯一名称,因此 ajax 函数知道在哪里查找。它可以这样做:
total = $.get("somefile-total.txt");
current = $.get("somefile-status.txt");
status = current/total;