我正在尝试在MVC操作中创建下载功能,并且实际的下载工作正常,但是文件是以actionname作为文件名保存的,例如,从下面的代码中,我得到了一个文件名'DownloadMP3‘。有谁知道如何在下载时保留原始文件名?
[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
}发布于 2012-05-25 15:52:17
Content-Disposition头的正确语法如下所示:
Content-Disposition: attachment; filename=foo.mp3但在本例中,您可以简单地使用File方法的重载,该方法接受3个参数,第三个参数是文件名。它将自动发出带有附件的Content-Disposition标头,这样您就不需要手动添加它(并且不需要像您那样在语法上犯错误)。
此外,您的filePath变量必须指向服务器上的物理文件,而不是相对url。使用Server.MapPath执行以下操作:
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);
}发布于 2012-05-25 15:54:14
只需将文件名放在内容处理中,而不是虚拟路径:
string fileOnly = fileName + ".mp3";
string filePath = @"~/Content/xxxxx/" + fileOnly;
Response.AddHeader("content-disposition", "attachment;" + fileOnly + ";");发布于 2012-05-25 15:54:43
尝试添加第三个参数
return File(file.FullPath, file.MimeType, file.FullName);https://stackoverflow.com/questions/10750540
复制相似问题