Skip to content
Advertisement

File not found exception on Symfony upload

I’m using Symfony 3.4 to work on a simple REST API microservice. There are not much resources to be found when working with HTTP APIs and file uploads. I’m following some of the instructions from the documentation but I found a wall.

What I want to do is to store the relative path to an uploaded file on an entity field, but it seems like the validation expects the field to be a full path.

Here’s some of my code:

JavaScript

Uploader Service:

JavaScript

I’ve registered the service:

JavaScript

And last the controller:

JavaScript

When I try to set the logo as a file basename string the request will fail. with error that the file (basename) is not found. This makes sense in a way.

If otherwise I try to set not a string but a File with valid path to the newly uploaded file the request will succeed, but the field in the table will be replaced with a full system path. The same happens when I put a valid system path instead of a file.

JavaScript

Parameter for the upload dir:

JavaScript

I’m not using any forms as this is a third party API and I’m mainly using the request objects directly to handle the data. Most of the documentations used Forms to handle this. Also all my responses are in JSON.

I’d appreciate any help on this. Otherwise I’ll have to store the full path and that in not a good idea and very impractical.

Thanks in advance.

Advertisement

Answer

Here is a thought on this: Instead of validating the property which your plan to be a relative path to an image, validate the method. Something like this maybe:

JavaScript

So, remove the validation from your logo member, add a new method (I named it getAbsolutePathLogo buy you can choose anything) and set up validation on top of it.

This way, your logo will be persisted as relative path and validation should work. However, the challenge now is to determine the right moment to set that static $basePath. In reality, this one does not even need to be a class static member, but could be something global:

JavaScript

Does this make sense?

Hope it helps a bit…

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement