Difference between FileContentResult and FileStrea

2020-02-26 04:58发布

I'm editing some code and there is one method which return FileContentResult type. I get a stream from service, so for me it would be more convenient to change returning type to FileStreamResult.

Should I convert stream to an array to return FileContentResult?

Or can I just change returning type safely?

2条回答
smile是对你的礼貌
2楼-- · 2020-02-26 05:18

Both FileStreamResult and FileContentResult inherit from FileResult which inherits from ActionResult. So you can return either one type from a method which has ActionResult as the return type

If you already have a stream, you can use FileStreamResult constructor to return a FileResult

public ActionResult Download()
{
    var f = Server.MapPath("~/Content/mypdf.pdf");
    var fileStream = new FileStream(f,FileMode.Open,FileAccess.Read);
    return new FileStreamResult(fileStream, MimeMapping.GetMimeMapping(f));
}

If you already have a byte arrray, you can use FileContentResult constructor to return a FileResult

public ActionResult Download()
{
    var f = Server.MapPath("~/Content/mypdf.pdf");
    var bytes = System.IO.File.ReadAllBytes(f);
    return new FileContentResult(bytes, MimeMapping.GetMimeMapping(f));
}

The Controller.File method has overloads which takes either a byte array or a stream

public ActionResult Download()
{
    var f = Server.MapPath("~/Content/mypdf.pdf");
    var bytes = System.IO.File.ReadAllBytes(f);
    return File(bytes, MimeMapping.GetMimeMapping(f));
}
public ActionResult Download2()
{
    var f = Server.MapPath("~/Content/mypdf.pdf");
    var fileStream = new FileStream(f, FileMode.Open, FileAccess.Read);
    return File(fileStream, MimeMapping.GetMimeMapping(f));
}

If the browser has the support to display the content type of the response, the response will be displayed in the browser. For example, for the above code, it will display the pdf content in the browser.

There is another overload of the File method which takes the download file name which the browsers' save/download dialog will use so that user can save it his local computer and/or open.

public ActionResult Download4()
{
    var f = Server.MapPath("~/Content/mypdf.pdf");
    var fileStream = new FileStream(f, FileMode.Open, FileAccess.Read);
    return File(fileStream, MimeMapping.GetMimeMapping(f),"MyfileNiceFileName.pdf");
}

With this, user will get a download prompt from the browser.

查看更多
Emotional °昔
3楼-- · 2020-02-26 05:38

FileResult is an abstract base class for all the others.

  • FileContentResult - use it when you have a byte array you would like to return as a file
  • FileStreamResult - you have a stream open, you want to return it's content as a file
查看更多
登录 后发表回答