1

我正在尝试在 MVC 操作中创建下载功能,并且实际下载有效,但是文件以操作名作为文件名保存,例如从下面的代码中我得到一个文件名“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

    }
4

3 回答 3

1

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-25T07:52:16.513 回答
0

只需将文件名放在内容配置中,而不是虚拟路径:

    string fileOnly = fileName + ".mp3";
    string filePath = @"~/Content/xxxxx/" + fileOnly;

    Response.AddHeader("content-disposition", "attachment;" + fileOnly + ";");
于 2012-05-25T07:54:13.600 回答
0

尝试添加第三个参数

return File(file.FullPath, file.MimeType, file.FullName);
于 2012-05-25T07:54:42.770 回答