getherbert / herbert

The WordPress Plugin Framework:
http://getherbert.com/
632 stars 94 forks source link

Serve static files via Controller. #75

Open jeremyzahner opened 9 years ago

jeremyzahner commented 9 years ago

Hi there

I was trying to serve files via a controller.

<?php namespace MyAppNamespace\Controllers;

use Herbert\Framework\Models\Post;
use Herbert\Framework\Http;

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

class MyPostController {
/**
 * Download the post attached pdf for the given id.
 * @param [type] $id [description]
 * @param Http $http [description]
 * @return file [description]
 */
public function download($id, Http $http)
{

    $post = Post::find($id);

    if(!$post)
    {
        return response('Label not found', 404);
    }

    $file = get_attached_file( get_field('post_pdf', $id)['id'] );
    $filename = basename($file);

    // prepare BinaryFileResponse
    $response = new BinaryFileResponse($file);
    $response->headers->set('Content-Type', 'application/pdf');
    $response->setContentDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT,
        $filename,
        iconv('UTF-8', 'ASCII//TRANSLIT', $filename)
    );
    $response->trustXSendfileTypeHeader();

    return response($response);

}

Also because of the router restriction i can not directly return my response.

Is there a easy way to get this working?

jasonagnew commented 9 years ago

For now you could do:

    public function download($id, Http $http)
    {
        $post = Post::find($id);

        if (!$post) {
            return response('Label not found', 404);
        }

        $file = get_attached_file($id);
        $filename = iconv('UTF-8', 'ASCII//TRANSLIT', basename($file));

        $headers = [];
        $headers['Content-Type'] = "application/pdf";
        $headers['Content-Disposition'] = "attachment; filename='{$filename}'";

        return response(file_get_contents($file), 200, $headers);
    }

It would make sense to have a standard (and better) way of returning a file within the framework.

jeremyzahner commented 9 years ago

Thanks!

If i find some time i could probably make a proposal on how to do it.