0

I'm developing a single page application using angular typescript and webapi. I'm trying to download some .exe files from my website. I have a download button on page, when user clicks on it the browse should prompt for the saved location and the .exe files should get downloaded to his local machine.

Please share your thoughts.

Thank you.

Harik.

Krish
  • 33
  • 3
  • 6
  • It's all about the headers. Take a look at this question http://stackoverflow.com/questions/11125535/microsoft-web-api-return-a-file-use-byte – smoksnes Jun 16 '16 at 06:52

2 Answers2

0

Just create link <a href="path_to_exe_file">Download</a>

Mikalai
  • 1,515
  • 8
  • 21
0

Well, 3 years late, but posting the answer here for future reference.

First, in your ASP.NET web api controller:-

[Route("downloadFile")]
[HttpGet]
public HttpResponseMessage DownloadFile()
{
    HttpResponseMessage res = null;
    try
    {
        res = new HttpResponseMessage(HttpStatusCode.OK);

        // if you are serving file from App_Data folder, otherwise set your path
        string path = HttpContext.Current.Server.MapPath("~/App_Data");

        res.Content = new StreamContent(new FileStream($"{path}\\app.exe", FileMode.Open, FileAccess.Read));

        res.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");

        res.Content.Headers.ContentDisposition.FileName = "app.exe";

        res.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/exe");

        return res;
    }
    catch(Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
    }
}

As you can see, the method to sending a .exe file to the client is exactly the same as sending .txt/.pdf file. You only need to change the ContentTypeto the proper type: applicaion/XXX.

You can then call the above api from your angular SPA using HttpClient or just put the url of your api inside of the href attribute of a tag:

<a href="http://localhost:XXXXX/url/to/downloadFile">Download</a>

Clicking on this a element will send a GET request to the above url and the file will be downloaded.