Oblomingo
Oblomingo

Reputation: 698

How to get file from FileStremResult object in Asp.Net MVC Web application?

I have Asp.Net MVC Web application with form. When I submit form app runs method:

[HttpPost]
public ActionResult MyMethod(MyViewModel model)
{
    FileStreamResult document = CreateDocument(model);
    return document;
} 

And browser opens generated file (PDF) in the same tab. I'm doesn't want to open this file, instead I want to download it to disk. How to implement this action?

Upvotes: 0

Views: 1909

Answers (2)

Slicksim
Slicksim

Reputation: 7172

You will need to tell the browser that it is a download, rather than a file.

You can do this by setting 2 headers (content type and content disposition), and then writing your PDF to the response stream.

[HttpPost]
public ActionResult MyMethod(MyViewModel model)
{

     HttpResponseBase response = ControllerContext.HttpContext.Response;

    response.ContentType = "application/pdf";
    response.AppendHeader("Content-Disposition", "attachment;filename=yourpdf.pdf");

    FileStreamResult document = CreateDocument(model);
    //Write you document to response.OutputStream here
    document.FileStream.Seek(0, SeekOrigin.Begin);
    document.FileStream.CopyTo(response.OutputStream, document.FileStream.Length);

    response.Flush();

    return new EmptyResult();
} 

Upvotes: 3

Erik J.
Erik J.

Reputation: 809

You should return a FileStreamResult (this will force a download together with the "FileDownloadName". By specifying an ActionResult as a method return value you have the flexibility of returning other stuff as well (HttpStatusCodes, View()'s, or Content()'s).

public ActionResult DownloadSomeFile()
    {
        using (var ms = new MemoryStream())
        {
            var response = GetMyPdfAsStream(); // implement this yourself
            if (response is StreamContent)
            {
                var responseContent = response as StreamContent;
                await responseContent.CopyToAsync(ms);
                byte[] file = ms.ToArray();
                MemoryStream output = new MemoryStream();
                output.Write(file, 0, file.Length);
                output.Position = 0;

                return new FileStreamResult(output, "application/pdf") { FileDownloadName = fileName };
            }
            else
            {
                return Content("Something went wrong: " + response.ReasonPhrase);
            }
            return null;
        }

    }

Upvotes: 0

Related Questions