I am trying to create download functionality in an MVC action, and the actual download works, but the file is saved with the actionname as the filename e.g. from the code below I get a filename of ‘DownloadMP3’. Does anybody know how to keep the original filename when downloading?
[Authorize]
public virtual FileResult DownloadMP3(string fileName)
{
//Actions/Download?filename=test
//test
string filePath = @"~/Content/xxxxx/" + fileName + ".mp3";
Response.AddHeader("content-disposition", "attachment;" + filePath + ";");
return File(filePath, "audio/mpeg3");
//for wav use audio/wav
}
The correct syntax of the Content-Disposition header is like this:
But in this case you could simply use the overload of the File method which takes 3 arguments, the third being the filename. It will automatically emit the Content-Disposition header with attachment so that you don’t need to manually add it (and make mistakes in its syntax as you did).
Also your
filePathvariable must point to the physical file on the server and not a relative url. UseServer.MapPathfor this: