Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the filename when downloading a file? [duplicate]

I'm working on MVC 4. I have generated Excel file dynamically using following simple code. My hosting is on Azure.

I have created a Root path and then try to save that Excel file.

Problem is when my ActionResult method response comes back it is giving default popup to open a file but file name is having a GUID instead my provided file name.

Excel file generation code:

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 returns path like C:\AppData\Local\dftmp\Resources\11a2435c-998c-4fe8-aa55-8bb42455b4ca\directory\DemoFile.xls.

The Download File popup does not give file name as DemoFile it gives some GUID why so?

enter image description here

ActionResult method code:

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

Also tried to give name property

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"
        };
    }

getting below error when give filename parameter. enter image description here

i have plenty of space and memory.

like image 965
Neo Avatar asked Oct 22 '25 06:10

Neo


1 Answers

You should return a new FileContentResult and your action must return FileResult instead of ActionResult for ex.:

public virtual FileResult DownloadFile(long fileId)
{
     string path = ExcelGenerationCode(fileName);
     return File(path, "application/vnd.ms-excel","donwload.xls");
}
like image 80
Vajda Endre Avatar answered Oct 24 '25 19:10

Vajda Endre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!