Title: Download byte array sent by web api as pdf on client
Tags: jquery;asp.net-mvc-4;asp.net-web-api;download
Question: I am exporting crystal report to a pdf document and there is a button in UI that downloads that pdf in "Downloads" folder. To achieve this I have a method in web api that gets executed on button click and that method returns HttpResponseMessage whose contents are the byte array (the pdf resides on blob and I download that file to a byte array).
From UI, using window.open method of javascript I am directly opening the URL of the web api method which when executed downloads the file in downloads folder.

This works fine. But now I have added [Authorize] attribute to the web api controller and hence when javascript window opens with the method URL, user is prompted for a user name and password value.

I am trying to post an ajax request to the server which returns me byte array on client. After the ajax request is executed, I have written the code below:

```data = "data:application/octet-stream;base64," + data;
document.location = data;
```

The file does get downloaded but it gets downloaded as a "download" file for which I have to use "Open with.." option to view the file. How can I download  it as a pdf document ?



Here is another answer: If you are trying to serve a file with WebApi, you can do this:

``` HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
 Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true);
 response.Content = new StreamContent(fileStream);
 response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
 response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
 response.Content.Headers.ContentDisposition.FileName = "myfilename.pdf";

  return response;
```

You don't need to manually dispose the stream, the framework calls HttpResponseMessage.Dispose, which calls StreamContent.Dispose, which calls FileStream.Dispose.

Comment for this answer: I had written similar code before and it works perfectly fine. But I have now decorated my web api controller with [Authorize] attribute. That is why I am sending byte[] from server to client. You can read the question again. I want to download that byte[] as pdf on client.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2014:00:03/25/14', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<jquery><asp.net-mvc-4><asp.net-web-api><download>', 'Title': 'Download byte array sent by web api as pdf on client', 'ViewCount': 4067, 'id': 22643399, 'user_AboutMe': None, 'user_AccountId': 3050653.0, 'user_DisplayName': 'user2585299', 'user_Reputation': 863.0, 'user_Views': 129.0, 'user_id': 2585299.0}}