0

I've been trying to store a binary file in my database using a controller. I have an entity with a blob field. How can I read the uploaded file, get its binary data and store it in my blob field?

So far I have this code:

  public function postPictureAction($slug, Request $request)
  {
    return $request->files;
  }

And I get back this:

  { 

   "parameters": {
        "picture": {
            "test": false,
            "original_name": "Untitled Diagram.png",
            "mime_type": "image/png",
            "size": 13423,
            "error": 0
        }
    },
    "file_keys": [
        "error",
        "name",
        "size",
        "tmp_name",
        "type"
    ]
}

So the file seems to be uploaded just fine, but now, where is it? how can I read it?

This code returns the file's mime type:

$picture->setType($file->getMimeType());

But this is just intuition, since I didn't find any documentation on the "file" class. Is there such documentation?

2 Answers 2

1

The path you are taking will get you out of Symfony2 you are going to a path where you will use native PHP, generate a form with 'file' as type to create you upload file returned as UploadFile object. Then if you really want to store your file as blob in the database and not using an upload folder as suggested in the docs : http://api.symfony.com/2.0/Symfony/Component/HttpFoundation/File/UploadedFile.html

You can use this :

public function upload(){  
    $file = $request->files->get('picture');   
    $entity->setBinary(file_get_contents($file)); //binary property of your entity class is the blob

    $entity_manager->persist($entity);
    $entity_manager->flush();

}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm aiming scalability and portability. What are your thoughts on this approach I described?
I would rather leave the images out of database and the entity i create will have the image metadata, then upload the images in a structured folders. that way you wont have to query heavy binary from database to get images, only metadata then get them from the uploaded folder
0

the file was not stored anywhere (not in a persistent place, is in the temporary directory for uploaded file as described in the php.ini, if the session ends, the file goes), it was just sent in the HTTP request, that's what you are reading back

here you can read more about file upload and Doctrine related stuff, though if you want to just store a file there's no need of using the Doctrine ORM

here the UploadFile API (HttpFoundation component) as you can see this class lives in a place far from the Doctrine ecosystem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.