0

So I have a MVC ASP.NET project, on a view when a button is clicked it should ask the user to save/open the file. But what it does is it opens the file in the browser. The file is a csv file.

Here is the code for the view

@using (Html.BeginForm("Download", "Home", new { name = ViewBag.Downloadfilename }, FormMethod.Post))
{
<button type="submit">Button 1</button>
 }

While the code for the controller is such

     public ActionResult Download(string name)
        {

            //string file = @"c:\someFolder\foo.xlsx";
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            string file = name;
          return File(file, Path.GetFileName(file));
        }

So anyone know how the controller can force the user to save the file instead of opening in browser. (using chrome).

Thanks

test
  • 85
  • 1
  • 10
  • 1
    any reason why you can't do this using Response.Headers...etc plenty of examples on how to simply do this online by the way.. – MethodMan Dec 24 '15 at 00:05
  • I had a look at them, but couldn't find anything download related. do you have any links? – test Dec 24 '15 at 00:09
  • I see where you created a string variable `contentType` - but you don't use it anywhere. I assume you were intending to use that variable as the value for the Content-Type HTTP header. – Sam Axe Dec 24 '15 at 00:09
  • Possible duplicate of [Open file in C#](http://stackoverflow.com/questions/10171470/open-file-in-c-sharp). Please search before posting. You title found multiple hits! – TFD Dec 24 '15 at 00:33

1 Answers1

1
  //Gives me a download prompt.
  return File(document.Data, document.ContentType, document.Name);


 //Opens if it is a known extension type, downloads otherwise (download has      bogus name and missing extension)
 return new FileStreamResult(new MemoryStream(document.Data), document.ContentType);

 //Gives me a download prompt (lose the ability to open by default if known type)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType) {FileDownloadName = document.Name};
eric_eri
  • 699
  • 11
  • 19