My ASP.NET MVC app accepts files uploaded and stores these in a single folder. However I want to ensure that when a user uploads a file the app accepts any filename, however this will fail when users try upload files with the same file name.
I guess I could create separate folders for each file but I’d like a clean and flat directory structure. Currently I append a GUID to the file name but this isn’t a nice solution as it results in weird filenames when a user downloads a file.
I thought about storing the file data in a database and then writing it out to a file when it was requested, but this is a lot of overhead.
Any alternative approaches?
In order to keep your directory structure flat store your files by appending a GUID (as you already did). In your download handler (controller action method) first convert the GUID based file name to the original file name by removing the GUID from the file name. Then use the
FileContentResultclass to transfer the file. You can set theFileDownloadNameproperty to specify the file name for the file to transfer. In fact theFileDownloadNameproperty sets the Content-Disposition header under the hood.Here is a small code example (action method of your download controller class):
The user downloading the file is prompted to open/save a file with the original file name.
Hope, this helps.