-1

I need download a file from a directory in Symfony. The problem is, I need download this file when I am authenticated.

For that, I create a endpoint (GET method) with an ID (the id file), and I am doing the call from a React app passing in the Headers an authorization bearer.

The problem is, the file is not download directly, but if I enter in DevTools from Chrome, I see that in the response exists the file, but it is not downloaded.

This is the PHP code:

$file = new File($fullPath);

return $this->file($file);

How could I download the file?

keepAlive
  • 6,369
  • 5
  • 24
  • 39
Agustin Herrera
  • 363
  • 5
  • 14
  • 1
    It's sounds bit stupid, but i solved it like in the first answer here: https://stackoverflow.com/questions/29452031/how-to-handle-file-downloads-with-jwt-based-authentication It's about Angular, but since its a general problem, the method stays the same. Since you cannot directly link it because of the authorization, you serve the file to your js ajax handler, and dynamically create a non visible link for it and click it programmatically, then remove the link-element. Sounds like a stupid workaround, but thats the way to go. – Benjamin Kozlowski Jan 29 '19 at 11:16
  • Perfect, works as a charm :D thank you! – Agustin Herrera Jan 29 '19 at 12:16

1 Answers1

1

This is an example code of mine:

/**
 * @param Product $product
 * @param TranslatorInterface $translator
 *
 * @SWG\Response(
 *     response=200,
 *     description="Get allergensheet of a product",
 * )
 * @SWG\Tag(name="Product")
 *
 * @Route("/allergensheet/{id}", methods="GET")
 *
 * @Security(name="Bearer")
 * @return Mixed
 */
public function downloadAllergenSheet(Product $product, TranslatorInterface $translator) {

    $allergens = $product->getAllergens();

    if($allergens instanceof Allergens) {

        if($allergens->getHasSheet()) {
            $fs = new Filesystem();

            if($fs->exists($translator->trans($product->getArticleNr() . '_allergensheet'))) {
                return new BinaryFileResponse($translator->trans($product->getArticleNr() . '_allergensheet'));
            }
            else {
                return new JsonResponse(false, Response::HTTP_NO_CONTENT);
            }

        }
        else {
            return new JsonResponse(false, Response::HTTP_NO_CONTENT);
        }

    }
    else {
        return new JsonResponse(false, Response::HTTP_NO_CONTENT);
    }

}

maybe this can help? This if for downloading a PDF file which contains some information about a product.