在给定的代码中,只有其他条件每次都在运行。我使用了pdf.js库并试图打破块中的pdf。我在服务器端使用此代码,但似乎只有其他条件正在运行,并且isset($_SERVER['HTTP_RANGE']
可能返回null
。所以pdf会在第一次加载时加载。
if(isset($_SERVER['HTTP_RANGE'])) {
$fp = @fopen($filepath, 'rb');
$size = filesize($filepath); // File size
$length = $size; // Content length
$start = 0; // Start byte
$end = $size - 1; // End byte
header("Accept-Ranges: 0-$length");
if (isset($_SERVER['HTTP_RANGE'])) {
$c_start = $start;
$c_end = $end;
// Extract the range string
list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
// Make sure the client hasn't sent us a multibyte range
if (strpos($range, ',') !== false) {
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
// (?) Echo some info to the client?
exit;
}
if ($range == '-') {
// The n-number of the last bytes is requested
$c_start = $size - substr($range, 1);
}
else {
$range = explode('-', $range);
$c_start = $range[0];
$c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
}
$c_end = ($c_end > $end) ? $end : $c_end;
// Validate the requested range and return an error if it's not correct.
if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
// (?) Echo some info to the client?
exit;
}
$start = $c_start;
$end = $c_end;
$length = $end - $start + 1; // Calculate new content length
fseek($fp, $start);
header('HTTP/1.1 206 Partial Content');
}
// Notify the client the byte range we'll be outputting
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: $length");
// Start buffered download
$buffer = 1024 * 8;
while(!feof($fp) && ($p = ftell($fp)) <= $end) {
if ($p + $buffer > $end) {
// In case we're only outputtin a chunk, make sure we don't
// read past the length
$buffer = $end - $p + 1;
}
set_time_limit(0); // Reset time limit for big files
echo fread($fp, $buffer);
flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
}
fclose($fp);
}
else {
header("Content-Length: ".filesize($filepath));
header("X-Sendfile: $filepath");
readfile($filepath);
}
答案 0 :(得分:1)
http://pdf.yt/的作者非常友好地发布了源代码 - 旧版本是用PHP编写的,它由PDF.js提供支持。有关完整解决方案,请参阅https://github.com/joepie91/pdfy/blob/master/public_html/modules/download.php。几乎是你的代码上面有正确的HTTP标题(例如“Accept-Ranges:bytes”)和几个解决方法。