Page MenuHomePhabricator

Technical Advice: How to output binary (image) data using the MediaWiki\Rest API?
Closed, ResolvedPublic


I understand that \MediaWiki\Rest\StringStream can be used as an argument to \MediaWiki\Rest\Response::setBody. I was guessing that I could use \MediaWiki\Rest\Stream to use an existing stream rather than a string.

				$stream = fopen( 'php://memory', 'r+' );
				$response->setBody( new Stream( $stream ) );
				foreach ( data as $byte ) {
					fwrite( $stream, $byte );
				fclose( $stream );

but it outputs

Warning: stream_copy_to_stream(): supplied resource is not a valid stream resource in /var/www/html/includes/Rest/Stream.php on line 16

Are there any uses of the Stream class where I can see how it is used correctly?

Event Timeline

In T221177 it is said:

The response contains the body text as a Psr\Http\Message\StreamInterface object. This may be a simple wrapper around a string. Guzzle (already a core dependency) provides several convenient classes derived from StreamInterface. Using Guzzle, a stream can be constructed which reads from a local file or HTTP client request.

Physikerwelt added a subscriber: Tgr.

Solved by @Tgr on irc. My iterm solution looks like this

				$response->setHeader( 'Content-Type', self::PNG_TYPE );
				$stream = fopen( 'php://memory', 'w' );
				$stream_obj = new Stream( $stream );
				$response->setBody( $stream_obj );
				foreach ( $payload->body->data as $byte ) {

So one needs to keep the stream open until the response has been sent.