Shilliene
Shilliene

Reputation: 11

How to send a file from REST API to front-end?

I am trying to write a service which builds an .ics calendar file from string (which works) and send it to front-end. Front-end gets that file as a result of an api query. This is how it looks on my side:

var dataBytes = Encoding.ASCII.GetBytes(icsString);
var dataStream = new MemoryStream(dataBytes);

HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(dataStream) };
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "file.ics" };
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

return httpResponseMessage;

Is it correct? If it should work, then how to get the data in JS on the front-end side?

Upvotes: 0

Views: 1907

Answers (1)

Vivek Nuna
Vivek Nuna

Reputation: 1

Your code looks fine, you need to close the fileStream and set responseStream Position to 0. You can refer to my code. and please make sure that file is present at the path and you are handling the exception

      //Copy the source file stream to MemoryStream and close the file stream
      MemoryStream responseStream = new MemoryStream();
      Stream fileStream = System.IO.File.Open(downloadFilePath, FileMode.Open);

      fileStream.CopyTo(responseStream);
      fileStream.Close();
      responseStream.Position = 0;

      HttpResponseMessage response = new HttpResponseMessage();
      response.StatusCode = HttpStatusCode.OK;

      //Write the memory stream to HttpResponseMessage content
      response.Content = new StreamContent(responseStream);
      string contentDisposition = string.Concat("attachment; filename=", fileName);
      response.Content.Headers.ContentDisposition = 
                    ContentDispositionHeaderValue.Parse(contentDisposition);
      return response;

Upvotes: 1

Related Questions