Download file from ASP.NET MVC 2

I'm currently trying to implement a controller where you can upload files (more specifically, jar archives). Files are stored on disk, not in the database. So far I have come up with the following:

public FilePathResult GetFile(String fileName) { return File(Path.Combine(Server.MapPath("~/App_Data/Bundles"), fileName), "application/java-archive"); } 

Ignore the lack of error handling and the like. The file is loaded this way, but it gets the wrong name. Instead, for example, the "sample.jar" file gets the controller name "GetFile" (without the extension).

Any ideas on what I'm doing wrong?

+4
source share
4 answers

Use overloading, which allows you to specify fileDownloadName .

 return File(Path.Combine(Server.MapPath("~/App_Data/Bundles"), fileName), "application/java-archive", fileName); 
+8
source

If they are simply stored on disk and you are not doing anything but just serving them, why route them using the controller? You should simply place them in ~/Content/Bundles , for example, and directly reference them.

Then you do not need to worry about all additional errors / security when working with the filename parameter. Also, as a rule, it is a bad practice to work with files directly from App_Data , because this is usually the place for files that should not be shared.

+2
source

File has an overloaded version, I mean that you need to add a third argument with the file name.

 return File(Path.Combine(Server.MapPath("~/App_Data/Bundles"), fileName), "application/java-archive", "putFileNamehere.extension"); 

Now putFileNamehere.extension will be displayed to the user in the File Download dialog box.

+1
source

Check out this link, it works as an option for uploading files using MVC 3

http://haacked.com/archive/2008/05/10/writing-a-custom-file-download-action-result-for-asp.net-mvc.aspx

+1
source

Source: https://habr.com/ru/post/1341831/


All Articles