Normally you would store file name with the extension.
What is the best way to store uploaded file paths/names?
I've been thinking about this for quite some time already. There are several ways (at least that I'm going to describe here) to store a file name in the database. For my examples I will use an example path "/storage/app/public/filename.png":
- /device/root/app/storage/public/filename.png
- /storage/public/filename.png
- /public/filename.png
- filename.png
- filename
After going over pro's and cons of all options there, I think that using just "filename.png" is the best all-round solution. Correct me if I'm wrong about any of this, but storing it like that is
- Environment-agnostic
- Still explicit (no mix-ups with extensions for example)
- Very easy to change the destination of this file to where ever, all you have to do is update the according disk (assuming there is one)
However to make this as easy to change as possible you need to add a disk for that file path in the filesystem config. So number 3 is my close 2nd place in that regard, where you don't need a custom filesystem disk, but if you were to change the location of the file, you'd need a script to also update all database records. So essentially for me it comes down to is should I leave it up to the database or codebase to decide the path to the file? Or is there a better solution I haven't mentioned here?
(Assume a simple case where a user uploads an avatar and I might want to use different storage providers on different envs, without changing the db or code preferably)
@joukebouke I normally prefer to go 1 step further by
- Storing the file as a unique UUID with no extension on the file system
- DB field uuid - file that is saved on the file system
- DB field name - Original uploaded name with extension
- Path should be decided in code and synced with file system, this will ensure good control without being affected by user data
The reasons are as follows:
- This allows any fancy filename without being constrained by the file system (i.e. NTFS is not fully compatible with EXT*)
- This allows for duplicate filenames without one overwriting the other
- This allows us to be flexible with the file paths without being limited by the path at time of saving
Hope it helps.
Please or to participate in this conversation.