Jump to content
Sign in to follow this  
NotionCommotion

Downloaded file has quotes around it.

Recommended Posts

Posted (edited)

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

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.