Jump to content

Recommended Posts

Nevermind.  Changed the following and it works:

->withHeader('Content-Disposition', 'attachment; filename="'.$name.'"')

When downloading a file, the name of the file is 'report.csv' (it literally has single quotes around it so Window's does recognize it as a CSV file).  I am obviously adding them, but I am not sure where.  The workflow is browser requests from webserver,  webserver performs cURL request to a second server, second server creates CSV file and returns it to webserver which returns it to browser client.  My code is below (I removed some unrelated script for briefness, but should have all pertinent code).  Do you see the culprit?  Any recommendations on how to troubleshoot?  Thanks

 

Browser Client

$('#list-header').on('click', '.download-data', function() {
    window.location.assign("/api/query/trend?parameters=foo&Accept=csv");
});

Webserver

$app->get('/api/query/trend', function(Request $request, Response $response) {
    $uri = $request->getUri();
    $path = substr($uri->getPath(), 4); //Remove "/api" from uri
    return $this->serverBridge->proxy($request->withUri($uri->withPath($path)), $response);
});

$c['serverBridge'] = function ($c) {
    return new \NotionCommotion\ServerBridge\ServerBridge(
        new \GuzzleHttp\Client([
            'base_uri' => $c['settings']['server']['scheme'].'://'.$c['settings']['server']['host'],
            'headers' => ['X-NotionCommotion-Key' => $c['settings']['server']['key']],
            'timeout'  => 30,
        ])
    );
};

class ServerBridge
{

    private $httpClient;

    public function __construct(\GuzzleHttp\Client $httpClient){
        $this->httpClient=$httpClient;  //Must be configured with default path
    }

    public function proxy(\Slim\Http\Request $slimRequest, \Slim\Http\Response $slimResponse):\Slim\Http\Response {
        //Forwards Slim Request to another server and returns the updated Slim Response.
        //TBD whether this method should change urlencoded body if provided to JSON and change Content-Type header.
        //TBD whether this method should change not send Slim request to Guzzle, but instead create a new Guzzle request and apply headers as applicable.
        $body=$slimRequest->getBody();
        $slimRequest=($contentType=$slimRequest->getContentType())
        ?$slimRequest->withUri($slimRequest->getUri()->withHost($this->getHost(false)))  //Change slim's host to API server!
        :$slimRequest->withUri($slimRequest->getUri()->withHost($this->getHost(false)))->withHeader('Content-Type', $contentType);  //And also apply Content-Type

        $guzzleResponse=$this->httpClient->send($slimRequest);
        //Blacklist headers which should not be changed.  TBD whether I should whitelist headers instead.
        $excludedHeaders=['Date', 'Server', 'X-Powered-By', 'Access-Control-Allow-Origin', 'Access-Control-Allow-Methods', 'Access-Control-Allow-Headers'];
        $headerArrays=array_diff_key($guzzleResponse->getHeaders(), array_flip($excludedHeaders));
        foreach($headerArrays as $headerName=>$headers) {
            foreach($headers as $headerValue) {
                $slimResponse=$slimResponse->withHeader($headerName, $headerValue);
            }
        }
        return $slimResponse->withStatus($guzzleResponse->getStatusCode())->withBody($guzzleResponse->getBody());
    }

    private function getHost(bool $includeSchema=true):string {
        $baseUri=$this->httpClient->getConfig()['base_uri'];
        return $includeSchema?$baseUri->getScheme().'://'.$baseUri->getHost():$baseUri->getHost();
    }
}

API Server

$app->get('/query/trend', function (Request $request, Response $response) {
    $dataObject = $this->trendService->query($request->getQueryParams());
    $responder = new ResponseContent\ResponseContentCsv($response);
    return $responder->respond($dataObject);
);

class ResponseContentCsv
{
    protected  $response;

    public function __construct(\Psr\Http\Message\ResponseInterface $response) {
        $this->response=$response;
    }

    public function respond($dataObject) {

        $stream = fopen('php://memory', 'w+');

        //Use fputcsv() to write to stream

        $name='report.csv';
        rewind($stream);

        return $this->response->withBody(new \Slim\Http\Stream($stream))
        //->setOutputBuffering(false)
        ->withHeader('Content-Description', 'File Transfer')
        ->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
        //->withHeader('Content-Type', 'text/csv')
        ->withHeader('Content-Disposition', "attachment; filename='$name'")
        ->withHeader('Expires', '0')
        //->withHeader('Content-Length', $doc->size),
        ->withHeader('Pragma', 'public');
    }
}

 

Edited by NotionCommotion
Figured out what I was doing wrong
Link to comment
https://forums.phpfreaks.com/topic/308669-downloaded-file-has-quotes-around-it/
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.