nginx零拷贝配置与实现

背景: nginx开启零拷贝之后,可以跳过(内核缓冲区->用户态->socket缓冲区)这一个过程,减少用户态到内核态的切换。

配置:nginx

sendfile:on;

问题:在开启了nginx零拷贝后,php生成一个压缩文件后怎么返回给浏览器?告知nginx要下载的是哪个文件,需要配置head信息?

传统下载方式:

static function flushFile($filePath, $type, $fileSize, $name)
{

    $localFile = fopen($filePath, 'r');

    header("Content-Type: " . $type);
    header("Accept-Range: bytes");
    header("Content-Length: " . $fileSize);
    header('Content-Disposition: attachment; filename="'. $name.'"');

    $buffer = 1024;
    while (!feof($localFile)) {
        echo fread($localFile, $buffer);
    }
    fclose($localFile);

}

网上有看到一个用例是配置X-Accel-Redirect属性如:
static function flushFile($filePath, $type, $fileSize, $name)

{
    header("Content-Type: " . $type);
    header("Accept-Range: bytes");
    header("Content-Length: " . $fileSize);
    header('Content-Disposition: attachment; filename="'. $name.'"');

    header('X-Accel-Redirect: '. $filePath);

}

但是这样浏览器会报错,响应无效,官方文档也找不到X-Accel-Redirect的相关信息

阅读 3.4k
2 个回答
✓ 已被采纳新手上路,请多包涵
public function download($filename, $filePath){
        // 校验通过后        
        header('Content-Type: application/octet-stream');           

        ob_start();
        readfile($filePath);
        $data = ob_get_contents();
        ob_end_clean();
        header('Accept-Length: '.strlen($data));
        $ua = $_SERVER["HTTP_USER_AGENT"];  // 处理不同浏览器的兼容性
        if (preg_match("/MSIE/", $ua) || preg_match("/rv:/", $ua)) {
            $encoded_filename = rawurlencode($filename);
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        } else if (preg_match("/Firefox/", $ua)) {
            header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
        } else {
            header('Content-Disposition: attachment; filename="' . $filename . '"');
        }
        echo $data;
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题