php使用HttpFoundation进行下载文件

本文介绍了如何在PHP中利用HttpFoundation组件来处理文件下载。首先,通过Composer安装HttpFoundation 3.4.*版本。接着,展示了项目的目录结构。重点在于`FileDownload.php`,它封装了HttpFoundation的下载功能,包括对中文文件名的支持。同时,还提供了一个`Util.php`辅助类。最后,`index.php`作为测试入口,用于实际调用文件下载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. php使用HttpFoundation进行下载文件–php处理下载

1、使用composer安装HttpFoundation组件

composer require symfony/http-foundation -v 3.4.*

2、目录结构
在这里插入图片描述
3、FileDownload.php对httpfoundation组件下载功能封装(支持中文文件名)

<?php
namespace download;

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Request;

class FileDownload extends BinaryFileResponse{
	/**
	 * 构造函数
	 * @param  string  $file               文件路径
	 * @param  integer $status             响应状态
	 * @param  array   $headers            响应头信息
	 * @param  boolean $public             Cache-Control
	 * @param  string  $contentDisposition Content-Disposition
	 * @param  boolean $autoEtag           Etag
	 * @param  boolean $autoLastModified   LastModified
	 * @return BinaryFileResponse
	 */
	public function __construct($file, $status = 200, $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
	{
        $file = $this->encoding($file, 'GBK', 'UTF-8');
        parent::__construct($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
	}

    /**
     * 使用php进行文件下载
     * @param  string $filename 显示文件名(不包含后缀)
     */
    public function download($showname = '')
    {
        $showname = $this->getShowName($showname);
    	$this->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $showname);

        $request = Request::createFromGlobals();
    	$this->prepare($request)->send();
    }

    /**
     * 使用X-SendFile进行文件下载
     * @param  string $filename 显示文件名(不包含后缀)
     */
    public function xDownload($showname, $Sendfile = 'X-Sendfile')
    {
        $showname = $this->getShowName($showname);

        $this->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $showname);

        $request = Request::createFromGlobals();
        $request->headers->set('X-Sendfile-Type', $Sendfile);
        //设置使用X-SendFile下载文件
        BinaryFileResponse::trustXSendfileTypeHeader();
        
        $this->prepare($request)->send();
    }
    
    /**
     * 获取显示文件名
     * @param  string $file 文件
     * @return string
     */
    protected function getShowName($file)
    {
        if(!empty($file))
        {
            return $file.'.'.$this->file->getExtension();
        }

        return $this->encoding($this->file->getBasename());
    }


    /**
     * 转换字符编码
     * @param  string $str 文件路径
     * @param  string $to   转换后的编码
     * @param  string $from 转换前的编码
     * @return string
     */
    protected function encoding($str, $to = 'UTF-8', $from = 'GBK')
    {
    	if(empty($str))
    	{
    		return false;
    	}

        if(Util::os() == 'WINNT')
        {
            return Util::convertEncoding($str, $to, $from);
        }
        
    	return $str;
    }

    /**
     * 修复与 HTTP 规范不兼容的问题
     * @param  Request $request 请求对象实例
     * @return this
     */
    public function prepare(Request $request)
    {
        if (!$this->headers->has('Content-Type'))
        {
            $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
        }

        if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL'))
        {
            $this->setProtocolVersion('1.1');
        }

        $this->ensureIEOverSSLCompatibility($request);

        $this->offset = 0;
        $this->maxlen = -1;

        if (false === $fileSize = $this->file->getSize())
        {
            return $this;
        }
        $this->headers->set('Content-Length', $fileSize);

        if (!$this->headers->has('Accept-Ranges'))
        {
            $this->headers->set('Accept-Ranges', $request->isMethodSafe(false) ? 'bytes' : 'none');
        }

        if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type'))
        {
            $type = $request->headers->get('X-Sendfile-Type');
            $path = $this->file->getRealPath();
            if (false === $path)
            {
                $path = $this->file->getPathname();
            }

            $path = $this->encoding($path);

            if ('x-accel-redirect' === strtolower($type))
            {
                foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping)
                {
                    $mapping = explode('=', $mapping, 2);

                    if (2 === \count($mapping))
                    {
                        $pathPrefix = trim($mapping[0]);
                        $location = trim($mapping[1]);

                        if (substr($path, 0, \strlen($pathPrefix)) === $pathPrefix)
                        {
                            $path = $location.substr($path, \strlen($pathPrefix));
                            $this->headers->set($type, $path);
                            $this->maxlen = 0;
                            break;
                        }
                    }
                }
            } 
            else 
            {
                $this->headers->set($type, $path);
                $this->maxlen = 0;
            }
        } 
        elseif ($request->headers->has('Range'))
        {
            if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range')))
            {
                $range = $request->headers->get('Range');

                list($start, $end) = explode('-', substr($range, 6), 2) + [0];

                $end = ('' === $end) ? $fileSize - 1 : (int) $end;

                if ('' === $start)
                {
                    $start = $fileSize - $end;
                    $end = $fileSize - 1;
                }
                else
                {
                    $start = (int) $start;
                }

                if ($start <= $end)
                {
                    if ($start < 0 || $end > $fileSize - 1)
                    {
                        $this->setStatusCode(416);
                        $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
                    }
                    elseif (0 !== $start || $end !== $fileSize - 1)
                    {
                        $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
                        $this->offset = $start;

                        $this->setStatusCode(206);
                        $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
                        $this->headers->set('Content-Length', $end - $start + 1);
                    }
                }
            }
        }
        
        return $this;
    }
    
    protected function hasValidIfRangeHeader($header)
    {
        if ($this->getEtag() === $header)
        {
            return true;
        }

        if (null === $lastModified = $this->getLastModified())
        {
            return false;
        }

        return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
    }
}

4、Util.php

<?php
namespace download;

class Util {
	/**
	 * 获取系统类型
	 * @return string
	 */
	public static function os(){
		return PHP_OS;
	}
    /**
     * 转换字符编码
     * @param  string $str  文件路径
     * @param  string $to   转换后的编码
     * @param  string $from 转换前的编码
     * @return string
     */
    public static function convertEncoding($str, $to = 'GBK', $from = 'UTF-8')
    {
    	if(empty($str))
    	{
    		return false;
    	}

    	return mb_convert_encoding($str, $to, $from);
    }
}

4、index.php 测试文件下载

<?php
require_once "./vendor/autoload.php";
require_once './download/FileDownload.php';
require_once './download/Util.php';

use download\FileDownload;

try
{
	$file = "./源码.zip";
	$fileDownload = FileDownload::create($file, 200);

	$fileDownload->download();
	//使用Xsendfile下载文件
	//$fileDownload->xdownload('测试源码');
	//自定义下载文件名(不包含后缀)
	//$fileDownload->download('测试');
	//下载后删除源文件
	//$fileDownload->deleteFileAfterSend(true)->download();

}
catch(Exception $e)
{
	echo $e->getMessage();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值