Force client to download a file

@param null $file
@param null $type
@param null $file_name
184357
public function download($file = null, $type = null, $file_name = null)
    {
        if (!empty($file) && @file_exists($file)) {
            if (is_null($file_name)) {
                $file_name_parts = explode('/', $file);
                $file_name = end( $file_name_parts );
            }
            $this->addHeader('Content-disposition', 'attachment; filename='.$file_name);
            $this->addHeader('Content-Type', 'application/force-download');
            $this->addHeader('Content-Transfer-Encoding', $type);
            $this->addHeader('Content-Length', filesize($file));
            $this->addHeader('Pragma', 'no-cache');
            $this->addHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0, public');
            $this->addHeader('Expires', '0'); 
            $this->renderHeaders();
            readfile( $file );
            exit;
        }
        return;
    }
1252461
protected function getDataFromFile($file, $type = 'application/json')
    {
        if (file_exists($file)) {
            $opts = [
                'http' => [
                    'header' => 'Content-Type: '.$type.'; charset=utf-8',
                ],
            ];

            $context = stream_context_create($opts);
            $data = file_get_contents($file, 0, $context);
            $json = $this->isJson($data, true);
            
            if (!$json) {
                throw new InvalidJsonException();
            }
            
            return $json;
        }

        throw new FileNotFoundException();
    }
835456
public static DownloadResponse downloadFile(Drive drive, File file) throws IOException {
    if (file == null) {
      return null;
    }
    
    return downloadFile(drive, file.getId());
  }
716763
public static function download($output, $content_type='text/plain', $filename=null) {
	$filename_postfix = ($filename) ? '; filename="'.$filename.'"' : '';
	
	// force download
	header('Content-Type: '.$content_type.'; charset=utf-8');
	header('Content-Disposition: attachment'.$filename_postfix);
	
	// write to browser
	echo $output;
}
661525
public function flush($file_content = null, $type = null)
    {
        if (!empty($file_content)) {
            if (empty($type)) {
                $finfo = new \finfo();
                $type = $finfo->buffer($file_content, FILEINFO_MIME);
            }
            $this->addHeader('Content-Type', $type);
            $this->renderHeaders();
            echo $file_content;
            exit;
        }
        return;
    }
513685
public function download($id = null, $file = null) {
		$type = $this->_controller->RequestHandler->prefers();
		$exportFileName = null;
		if (method_exists($this->_model, 'getExportFilename')) {
			$exportFileName = $this->_model->getExportFilename($id, true);
		}

		$exportPath = $this->_getExportDir();
		$downloadFile = $exportPath . $file;
		if (!empty($type)) {
			$downloadFile .= '.' . $type;
		}

		if (!file_exists($downloadFile)) {
			throw new InternalErrorException(__d('view_extension', 'Invalid file for downloading'));
		}

		if (!empty($type) && !empty($exportFileName)) {
			$this->_controller->response->type($type);
			$exportFileName .= '.' . $type;
		}
		$responseOpt = [
			'download' => true,
		];
		if (!empty($exportFileName)) {
			if ($this->_controller->request->is('msie')) {
				$exportFileName = rawurlencode($exportFileName);
			}
			$responseOpt['name'] = $exportFileName;
		}
		$this->_controller->response->file($downloadFile, $responseOpt);

		return $this->_controller->response;
	}
796254
public function download(string $file, ?string $name = null, ?array $headers = [])
  {
    return Rest::download(self::url($file), $name, $headers);
  }
1339069
public function get_file($file, $type, $folder = '')
	{
		if ($file = $this->find_file($file, $type, $folder))
		{
			return $this->_asset_url.$file;
		}

		return false;
	}
1065556
public function downloadFileIndirectly($file, $content_type = null, $down_name = null)
    {
        if (!file_exists($file)) {
            throw new \Exception("No such file there: " . $file, 404);
        }

        if ($down_name !== null && $down_name !== false) {
            $extension = substr($file, strrpos($file, '.')); //获取文件后缀
            $down_name = $down_name . $extension; //新文件名，就是下载后的名字
        } else {
            $k = pathinfo($file);
            $extension = $k['extension'];
            $down_name = $k['filename'] . '.' . $extension;
        }

        $fp = fopen($file, "r");
        $file_size = filesize($file);

        if ($content_type === null) {
            // @since 1.5.0 The default $content_type for NULL would not be self::CONTENT_TYPE_OCTET_STREAM any more
            // but use MimeTypes to parse from extension.
            $content_type = $this->getMimeTypeByExtension($extension);
        }
        if ($content_type === self::CONTENT_TYPE_OCTET_STREAM) {
            $content_disposition = 'attachment; filename=' . $down_name;
        } else {
            $content_disposition = 'inline';
        }

        // Headers
        header("Content-Type: " . $content_type);
        //header("Accept-Ranges: bytes");
        header("Content-Length: " . $file_size);
        header("Content-Disposition: " . $content_disposition);
        $bufferSize = 1024;
        $fileSentBytesCount = 0;

        // Write to client
        while (!feof($fp) && $fileSentBytesCount < $file_size) {
            $buffer = fread($fp, $bufferSize);
            $fileSentBytesCount += $bufferSize;
            echo $buffer;
            /**
             * This flush added @since 2.3 try to make the save dialog comes soon
             */
            flush();
        }
        fclose($fp);
        return true;
    }
435999
public function checkRequest($type, $file)
    {
        // no checks for getters
        if(in_array($type, ['detectors', 'mime-types', 'parsers', 'version']))
        {
            //
        }
        // invalid local file
        elseif(!preg_match('/^http/', $file) && !file_exists($file))
        {
            throw new Exception("File $file can't be opened");
        }
        // invalid remote file
        elseif(preg_match('/^http/', $file) && !preg_match('/200/', get_headers($file)[0]))
        {
            throw new Exception("File $file can't be opened", 2);
        }
        // download remote file if required only for integrated downloader
        elseif(preg_match('/^http/', $file) && $this->downloadRemote)
        {
            $file = $this->downloadFile($file);
        }

        return $file;
    }
70371
public function download($file_name)
	{
		if (!\Entrust::can('download-logs')) {
	        abort(403, 'Unauthorized access - you do not have the necessary permission to download logs.');
	    }

		$disk = Storage::disk('local');

		if ($disk->exists('logs/'.$file_name)) {
			return response()->download(storage_path('logs/'.$file_name));
		}
		else
		{
			abort(404, "The log file doesn't exist.");
		}
	}
453176
public static function file($path, $type = null)
    {
        $response = new self(
            Status::OK,
            new PhpStream($path, 'rb')
        );
        if (isset($type)) {
            $response->setHeader('Content-Type', $type);
        }
        return $response;
    }
581422
public function download($file, $filename = '', $options = array())
    {
        $readfile = empty($options['text']);

        if ($readfile && !is_file($file)) {
            return null;
        }

        if ($readfile && empty($filename)) {
            $filename = basename($file);
        }

        $size = $readfile ? filesize($file) : strlen($file);

        $this->addHeader('Expires', 0)
            ->addHeader('Pragma', 'public')
            ->addHeader('Content-Length', $size)
            ->addHeader('Cache-Control', 'must-revalidate')
            ->addHeader('Content-Description', 'File Transfer')
            ->addHeader('Content-Type', 'application/octet-stream')
            ->addHeader('Content-Disposition', 'attachment; filename=' . $filename)
            ->addOptionalHeaders($options)
            ->sendHeaders();

        if ($readfile) {
            readfile($file);
        } else {
            echo $file;
        }

        exit;
    }
651129
public function load($file, $type = null)
    {
        $path   = $this->locator->locate($file);
        $config = array();

        $result = parse_ini_file($path, true);
        if (false === $result || array() === $result) {
            throw new InvalidArgumentException(sprintf('The "%s" file is not valid.', $file));
        }

        if (isset($result['parameters']) && is_array($result['parameters'])) {
            $config['parameters'] = array();
            foreach ($result['parameters'] as $key => $value) {
                $config['parameters'][$key] = $value;
            }
        }
    }
938330
public function get($remote_file = null, $local_file = null, $mode = FTP_ASCII)
    {
        if (\ftp_get($this->_stream, $local_file, $remote_file, $mode)) {
            return true;
        }

        $this->error = 'Failed to download file "'.$remote_file.'"';

        return false;
    }
1164741
public function getNewFile($type = null)
    {
        $class = $this->getFileModelName($type);
        /** @var ModelFile $file */
        $file = new $class();
        $file->setModel($this);
        $file->setFilesystem($this->getFilesystemDisk());
        return $file;
    }
1211305
public function forceDownload()
    {


        if ($this->type == "jpg")

    {
            $this->toJpg();

        } elseif ($this->type == "png") {

            $this->toPng();

        } elseif ($this->type == "gif") {

            $this->toGif();
        }

        header('Content-Description: File Transfer');
        header("Content-Type: application/octet-stream");
        header('Content-Length: ' . filesize($this->path));
        header('Content-Disposition: attachment; filename="' . basename($this->path.'"'));
        readfile($this->path);

        //remove the temp file
        unlink($this->path);

    }