0

I have a web api that need to let the user download/inline a binary file I have saved to a database.

So far now I could achieve it like this:

string ContentType = (string) (result["content_type"] ?? "");
string FileName = (string) (result["file_name"] ?? "");
byte[] content = (byte[]) result["data"];

Stream stream = new MemoryStream(content);
var fullFileName = Path.GetTempFileName();
File.WriteAllBytes(fullFileName, content);

_res.ContentType = ContentType;
_res.StatusCode = (int)HttpStatusCode.OK;
_res.Headers.Add("Content-Disposition", $"{Disposition}; filename=\"{FileName}\"");
await _res.SendFileAsync(fullFileName);

I'd like to know how could I send directly the memory stream to the response, in order to avoid saving the file to disk.

opensas
  • 60,462
  • 79
  • 252
  • 386

2 Answers2

1

You'll want to use HttpResponse.BinaryWrite or MemoryStream.WriteTo:

Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=file.xls");
Response.BinaryWrite(myByteArray);
// myMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
jspcal
  • 50,847
  • 7
  • 72
  • 76
0

I found an easier way

string ContentType = (string) (result["content_type"] ?? "");
string FileName = (string) (result["file_name"] ?? "");
byte[] content = (byte[]) result["data"];

_res.ContentType = ContentType;
_res.ContentLength = content.Length;
_res.StatusCode = (int)HttpStatusCode.OK;
_res.Headers.Add("Content-Disposition", $"{Disposition}; filename=\"{FileName}\"");

await _res.Body.WriteAsync(content, 0, content.Length);
opensas
  • 60,462
  • 79
  • 252
  • 386