下载文件时如何设置文件名?

我正在使用MVC 4.我使用以下简单的代码dynamic生成Excel文件。 我的托pipe在Azure上。

我创build了一个根path,然后尝试保存该Excel文件。

问题是当我的ActionResult方法响应回来它给予默认的popup来打开一个文件,但文件名是有一个GUID而不是我提供的文件名。

Excel文件生成代码:

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

 // ... //Save LocalResource resource = RoleEnvironment.GetLocalResource("MyValue"); string tempPath = resource.RootPath + "DemoFile.xls"; return tempPath; 

tempPath返回类似于C:\AppData\Local\dftmp\Resources\11a2435c-998c-4fe8-aa55-8bb42455b4ca\directory\DemoFile.xls

下载文件popup不会给文件名作为DemoFilegives some GUID为什么这样?

在这里输入图像说明

ActionResult方法代码:

 public ActionResult DownloadExcel() { string path = ExcelGenerationCode(fileName); Stream s = new FileStream(path, FileMode.Open, FileAccess.Read); return new FileStreamResult(s, "application/vnd.ms-excel"); } 

也试图给名称属性

 public ActionResult DownloadExcel() { string path = ExcelGenerationCode(fileName); Stream s = new FileStream(path, FileMode.Open, FileAccess.Read); return new FileStreamResult(s, "application/vnd.ms-excel") { FileDownloadName = "myexcelFILE1.xls" }; } 

给文件名参数时得到低于错误。 在这里输入图像说明

我有足够的空间和记忆。

您应该返回一个新的FileContentResult,并且您的操作必须是FileResult而不是ActionResult,例如:

 public virtual FileResult DownloadFile(long fileId) { string path = ExcelGenerationCode(fileName); return File(path, "application/vnd.ms-excel","donwload.xls"); }