Read complete story

Controller for upload and download files in Symfony

Here we will learn how to make a controller to upload a file and download the file in Symfony. Its quiet easy as in Symfony its quiet similar to how you do it in core PHP. So lets start! We are creating a controller which will upload a file and save its entry in a database table let the Entity that correspond to the Database Table is ‘UploadedFile’. Our entity ‘ UploadedFile’ will have 4 columns:

  1. FileId : Primary key, ID.
  2. FileName : The changed name by which file will be saved.
  3. ActualName: Actual name of the file uploaded.
  4. CreationTime: Its a extra field just in case you want to know the time of request.

So lets start with our controller thats DefaultController, we have to create an action lets take uploadAction() so the controller will look like

Now we have to create a parameter named ‘file_directory’ in config.yml file to declare the path where the file is to be stored. So go to app/config/config.yml and add the below mentioned line under ‘parameters:‘ tag

Now its done when you will upload a file now the file will be stored in the path with a different name and you can see the entry in database. Now send your file as a form data and you can see this working.

Its time for the next step, as now we have file in our system so we are creating an action to download that file. You can take any way to distinguish between files but here I am using FileId so our link (route) will have FileId in it as

And you are ready to go! Access the link and you will have your file downloaded with the name it was uploaded not with the name it was saved on your server. For more info go to Symfony Components.

. . .

Comment (1)

Add Your Comment

  • azkanurunala
    i cannot get the file with $request->files->get(‘file-name’);
    it returns null
  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close