开发者

Strategies For Creating Unique File Names/Locations for Uploaded Files

开发者 https://www.devze.com 2023-04-04 14:43 出处:网络
My ASP.NET MVC app accepts files uploaded and stores these in a single folder. However I want to ens开发者_JAVA百科ure that when a user uploads a file the app accepts any filename, however this will f

My ASP.NET MVC app accepts files uploaded and stores these in a single folder. However I want to ens开发者_JAVA百科ure 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 FileContentResult class to transfer the file. You can set the FileDownloadName property to specify the file name for the file to transfer. In fact the FileDownloadName property sets the Content-Disposition header under the hood.

Here is a small code example (action method of your download controller class):

string fileToDownload = "test.jpg_4274B9D4-9084-441C-9617-EAD03CC9F47F";

string originalFileName = fileToDownload.Substring(0, fileToDownload.LastIndexOf('_'));

FileContentResult result = new FileContentResult(
    System.IO.File.ReadAllBytes(Server.MapPath(String.Format("~/files/{0}", fileToDownload))), "application/binary");

result.FileDownloadName = originalFileName; // Sets the Content-Disposition header

return result;

The user downloading the file is prompted to open/save a file with the original file name.

Hope, this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消