abernard
abernard

Reputation: 231

How can I download files from database

I have a FileController with an addAction method, which stores one or more files in my database :

$files = [];

$form = $this->createForm(MultipleFilesType::class, []);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {

    $files = $form->get("files")->getData();


    foreach ($files as $key => $file)
    {
        /* @var $uploadedFile UploadedFile */
        $uploadedFile = $file["file"];

        if ($uploadedFile->getError()) {
            $request->getSession()->getFlashBag()->add('warning', $uploadedFile->getErrorMessage());
        } else {

            $file = (new File())
                    ->setName($uploadedFile->getClientOriginalName())
                    ->setContent(file_get_contents($uploadedFile->getPathname()))
                    ->setType($uploadedFile->guessExtension())
            ;

            $this->manager()->persist($file);
            $this->manager()->flush();


        }
    }
    // ...
}

And then I have a downloadAction:

public function _downloadAction($file, Request $request) 
{
    $response = new Response();
    $response->setContent($file->getContent());

    $d = $response->headers->makeDisposition(
        ResponseHeaderBag::DISPOSITION_ATTACHMENT, preg_replace('/[^a-zA-Z0-9-_\. ]/', "", $file->getName()) 
    );

    $response->headers->set("Content-Type", $file->getType());
    $response->headers->set('Content-Disposition', $d);

    return $response; 
}

So I tried with all the code above. My files seem to upload just fine, but when I try to download, I'm facing some issues depending of the type of file.

HTML and EML files work fine. Microsoft office type files (odt, xml, etc) : can't open them because they are corrupt. Image files: I get a "This is not a XX type file, file start with 0xc3 0xbf"

So... What is wrong in my code ? Maybe there are some ways I can do that better, but I'm new to file uploading / downloading and I'm struggling quite a bit. Also, assume I HAVE TO use database to store the file.

EDIT :

I tried a dump(file_get_contents($uploadedFile->getPathname())); in the addAction method, and dump($file->getContent()); in _downloadAction.

The results are very differents (and they shouldn't be !!). The first dump shows a lot of mysterious characters like : ▓│┤ÁÂÀ©╣║┬├─┼ãÃ╚╔╩ÊËÈıÍÎÏ┘┌ßÔÒõÕµþÞÚÛ±‗¾¶§÷

and the second one uses almost only alphanumerical characters.

I guess I should indeed try to escape characters when I store the content in the database. I tried mysql_escape_string(file_get_contents($uploadedFile->getPathname())) but it doesn't solve the problem. The original content and the downloaded one are still differents.

Upvotes: 1

Views: 688

Answers (1)

abernard
abernard

Reputation: 231

So, I finally managed to do it, with a combination of base64_encode() in the addAction method and base64_decode() in the downloadAction method().

Upvotes: 1

Related Questions