Prepare attachment headers to response object.

@param  ResponseInterface $response The response object.
@param  string            $filename Download file name.

@return  ResponseInterface
173872
public static function prepareAttachmentHeaders(
        ResponseInterface $response,
        ?string $filename = null
    ): ResponseInterface {
        $response = $response->withHeader('Content-Type', 'application/octet-stream')
            ->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate')
            ->withHeader('Content-Transfer-Encoding', 'binary')
            ->withHeader('Content-Encoding', 'none');

        if ($filename !== null) {
            $response = $response->withHeader(
                'Content-Disposition',
                'attachment; filename*=utf-8\'\'' . rawurlencode($filename)
            );
        }

        return $response;
    }
256312
public function sendFile($filedata)
    {
        $response = new HTTPResponse($filedata['body']);
        if (preg_match("#MSIE\s(6|7|8)?\.0#", $_SERVER['HTTP_USER_AGENT'])) {
            // IE headers
            $response->addHeader("Cache-Control", "public");
            $response->addHeader("Content-Disposition", "attachment; filename=\"".basename($filedata['name'])."\"");
            $response->addHeader("Content-Type", "application/force-download");
            $response->addHeader("Content-Type", "application/octet-stream");
            $response->addHeader("Content-Type", "application/download");
            $response->addHeader("Content-Type", $filedata['mime']);
            $response->addHeader("Content-Description", "File Transfer");
            $response->addHeader("Content-Length", $filedata['size']);
        } else {
            // Everyone else
            $response->addHeader("Content-Type", $filedata['mime']."; name=\"".addslashes($filedata['name'])."\"");
            $response->addHeader("Content-disposition", "attachment; filename=".addslashes($filedata['name']));
            $response->addHeader("Content-Length", $filedata['size']);
        }
        return $response;
    }
904171
private function getConvertedResponse(Request $request, Response $response)
    {
        $response = $response->withHeader(
            'Content-Disposition',
            'attachment; filename="'.
            $this->video->getFileNameWithExtension($request->getQueryParam('customFormat')).'"'
        );
        $response = $response->withHeader('Content-Type', 'video/'.$request->getQueryParam('customFormat'));

        if ($request->isGet() || $request->isPost()) {
            $process = $this->video->getConvertedStream(
                $request->getQueryParam('customBitrate'),
                $request->getQueryParam('customFormat')
            );
            $response = $response->withBody(new Stream($process));
        }

        return $response;
    }
315141
public function buildGetContentResponse(Response $response, FileDocument $file)
    {
        /** @var FileMetadataBase $metadata */
        $metadata = $file->getMetadata();
        if (!$metadata) {
            throw new InvalidArgumentException('Loaded file have no valid metadata');
        }

        // We use file's mimeType, just in case none we use DB's.
        $mimeType = null;

        if ($this->readFileSystemMimeType) {
            $mimeType = $this->fileSystem->getMimetype($file->getId());
        }
        if (!$mimeType) {
            $mimeType = $metadata->getMime();
        }
        if ($this->allowedMimeTypes && !in_array($mimeType, $this->allowedMimeTypes)) {
            throw new InvalidArgumentException('File mime type: '.$mimeType.' is not allowed as response.');
        }

        // Create Response
        $disposition = $response->headers->makeDisposition(
            ResponseHeaderBag::DISPOSITION_INLINE,
            $metadata->getFilename()
        );

        $response
            ->setStatusCode(Response::HTTP_OK)
            ->setContent($this->fileSystem->read($file->getId()));
        $response
            ->headers->set('Content-Type', $mimeType);
        $response
            ->headers->set('Content-Disposition', $disposition);
        return $response;
    }
1035967
public static void setFileDownloadHeader(final HttpServletResponse response, final String filename) {
		// 中文文件名支持
		String encodedFilename = Encodes.urlEncode(filename);
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFilename + '\"');
	}
832441
public function download($date, $filename = null, $headers = [])
    {
        if (is_null($filename)) {
            $filename = "laravel-{$date}.log";
        }

        $path = $this->filesystem->path($date);

        return response()->download($path, $filename, $headers);
    }
129447
public function getResponse($format, $filename, SourceIteratorInterface $source)
    {
        switch ($format) {
            case 'xls':
                $writer = new XlsWriter('php://output');
                $contentType = 'application/vnd.ms-excel';

                break;
            case 'xml':
                $writer = new XmlWriter('php://output');
                $contentType = 'text/xml';

                break;
            case 'json':
                $writer = new JsonWriter('php://output');
                $contentType = 'application/json';

                break;
            case 'csv':
                $writer = new CsvWriter('php://output', ',', '"', '\\', true, true);
                $contentType = 'text/csv';

                break;
            default:
                throw new \RuntimeException('Invalid format');
        }

        $callback = static function () use ($source, $writer) {
            $handler = Handler::create($source, $writer);
            $handler->export();
        };

        return new StreamedResponse($callback, 200, [
            'Content-Type' => $contentType,
            'Content-Disposition' => sprintf('attachment; filename="%s"', $filename),
        ]);
    }
927784
protected function finalizeResponse(ResponseInterface $response) : ResponseInterface
    {
        // stop PHP sending a Content-Type automatically
        ini_set('default_mimetype', '');
        if ($this->isEmptyResponseCode($response->getStatusCode())) {
            return $response->withoutHeader('Content-Type')->withoutHeader('Content-Length');
        }

        return $response;
    }
143469
public static function setHeadersFromBrowserResponse(Response $response,
            MessageInterface $browserResponse)
    {
        $heasers_resp = Utils::getHeadersFromBrowserResponse($browserResponse);
        foreach($heasers_resp as $key => $value)
        {
            if(strtolower($key) !== "transfer-encoding"){
                $response->headers->set($key, $value);
            }
        }
    }
892008
protected function getMetadataFromHeaders(Response $response) {
    $last_modified = \DateTime::createFromFormat(
        \DateTime::RFC1123,
        $response->getHeader('Last-Modified')[0]
    );

    // NonRDFSource's are considered files.  Everything else is a
    // directory.
    $type = 'dir';
    $links = Psr7\parse_header($response->getHeader('Link'));
    foreach ($links as $link) {
      if ($link['rel'] == 'type' && $link[0] == '<http://www.w3.org/ns/ldp#NonRDFSource>') {
        $type = 'file';
        break;
      }
    }

    $meta = [
      'type' => $type,
      'timestamp' => $last_modified->getTimestamp(),
    ];

    if ($type == 'file') {
      $meta['size'] = $response->getHeader('Content-Length')[0];
      $meta['mimetype'] = $response->getHeader('Content-Type')[0];
    }

    return $meta;
  }
537236
private function includeResponse(string $method, string $file, ResponseInterface $response) : ResponseInterface
    {
        ob_start();
        $content = ob_get_clean();
        $this->$method($file);
        $body = $response->getBody();
        $body->write($content);
        return $response->withBody($body);
    }
1280018
public function download($filename)
    {
        return $this->response->withFile($this->getPath($filename, false), ['download' => true]);
    }
1323219
public static function sendResponse(ResponseInterface $response)
    {
        header('HTTP/'.$response->getHttpVersion().' '.$response->getStatus().' '.$response->getStatusText());
        foreach ($response->getHeaders() as $key => $value) {
            foreach ($value as $k => $v) {
                if (0 === $k) {
                    header($key.': '.$v);
                } else {
                    header($key.': '.$v, false);
                }
            }
        }

        $body = $response->getBody();
        if (null === $body) {
            return;
        }

        if (is_callable($body)) {
            $body();

            return;
        }

        $contentLength = $response->getHeader('Content-Length');
        if (null !== $contentLength) {
            $output = fopen('php://output', 'wb');
            if (is_resource($body) && 'stream' == get_resource_type($body)) {
                if (PHP_INT_SIZE !== 4) {
                    // use the dedicated function on 64 Bit systems
                    stream_copy_to_stream($body, $output, (int) $contentLength);
                } else {
                    // workaround for 32 Bit systems to avoid stream_copy_to_stream
                    while (!feof($body)) {
                        fwrite($output, fread($body, 8192));
                    }
                }
            } else {
                fwrite($output, $body, (int) $contentLength);
            }
        } else {
            file_put_contents('php://output', $body);
        }

        if (is_resource($body)) {
            fclose($body);
        }
    }
1341374
public function prepareCache(ResponseInterface $response)
    {
        /** @var MessageInterface|ResponseInterface $response */

        // Force cachable
        if ($this->getCachable() === static::CACHE_ENABLE) {
            // Expires.
            $response = $response->withoutHeader('Expires')->withHeader(
                'Expires',
                gmdate('D, d M Y H:i:s', time() + 900) . ' GMT'
            );

            // Last modified.
            if ($this->modifiedDate instanceof \DateTime) {
                $this->modifiedDate->setTimezone(new \DateTimeZone('UTC'));

                $response = $response->withoutHeader('Last-Modified')->withHeader(
                    'Last-Modified',
                    $this->modifiedDate->format('D, d M Y H:i:s') . ' GMT'
                );
            }
        } elseif ($this->getCachable() === static::CACHE_DISABLE) {
            // Force uncachable

            // Expires in the past.
            $response = $response->withoutHeader('Expires')->withHeader('Expires', 'Mon, 1 Jan 2001 00:00:00 GMT');

            // Always modified.
            $response = $response->withoutHeader('Last-Modified')->withHeader(
                'Last-Modified',
                gmdate('D, d M Y H:i:s') . ' GMT'
            );
            $response = $response->withoutHeader('Cache-Control')->withHeader(
                'Cache-Control',
                'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
            );

            // HTTP 1.0
            $response = $response->withHeader('pragma', 'no-cache');
        }

        return $response;
    }
508486
protected function file($file, string $fileName = null, string $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
    {
        $response = new BinaryFileResponse($file);
        $response->setContentDisposition($disposition, null === $fileName ? $response->getFile()->getFilename() : $fileName);

        return $response;
    }
1174244
public function download($file, $name = null, array $headers = array(), $disposition = 'attachment')
	{
		$response = new BinaryFileResponse($file, 200, $headers, true, $disposition);

		if ( ! is_null($name))
		{
			return $response->setContentDisposition($disposition, $name, str_replace('%', '', Str::ascii($name)));
		}

		return $response;
	}
566993
private function createResourceResponse($filename)
    {
        $response = new Response();

        $filestats = stat($filename);

        $response->headers->set('Content-Type', MimeType::getInstance()->guess($filename));
        $response->headers->set('Content-Length', $filestats['size']);

        $response->setCache(array(
            'etag'          => basename($filename),
            'last_modified' => new \DateTime('@'.$filestats['mtime']),
            'public'        => 'public',
        ));

        $response->setContent(file_get_contents($filename));

        return $response;
    }