开发者

Download file from ASP.NET MVC 2 site

I'm currently trying to implement a controller where you can download files from (more specifically jar-archives). The files are stored on disk and not in database. So far I have come up with this:

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

Nevermind the lack of error handling and such at this time. The file do get downloaded this way, however it gets the wrong name. Instead of, for example, "sample.jar" the file gets the controller's name, "GetFile", (without extension).

Any ideas on what I am doing wrong?


Use the overload which allows you to specify the fileDownloadName.

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


If they are just stored on disk and you aren't doing anything other than just serving them why route them using the controller at all? You should just put them in ~/Content/Bundles for example and link to them directly.

Then you don't have to worry about all the extra error/security handling on the filename parameter. Also typically it's a bad practice to serve files straight out of App_Data because generally this is the location for files that shouldn't be shared.


The File has an overloaded version, I mean you have to add a 3rd 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 shown to the user in the File Download dialogue.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜