Reputation: 13773
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
}
Upvotes: 1
Views: 911
Reputation: 1038820
The correct syntax of the Content-Disposition header is like this:
Content-Disposition: attachment; filename=foo.mp3
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 filePath
variable must point to the physical file on the server and not a relative url. Use Server.MapPath
for this:
public virtual ActionResult DownloadMP3(string fileName)
{
var downloadPath = Server.MapPath("~/Content/xxxxx/");
fileName = Path.ChangeExtension(Path.GetFileName(fileName), "mp3");
var file = Path.Combine(downloadPath, fileName);
return File(file, "audio/mpeg3", fileName);
}
Upvotes: 1
Reputation: 1538
Try to Add third parameter
return File(file.FullPath, file.MimeType, file.FullName);
Upvotes: 0
Reputation: 700342
Just put the file name in the content disposition, not the virtual path:
string fileOnly = fileName + ".mp3";
string filePath = @"~/Content/xxxxx/" + fileOnly;
Response.AddHeader("content-disposition", "attachment;" + fileOnly + ";");
Upvotes: 0