【问题标题】:How to download .exe files from SPA using angularjs webapi如何使用 angularjs webapi 从 SPA 下载 .exe 文件
【发布时间】:2016-10-17 12:32:33
【问题描述】:

我正在使用 angular typescript 和 webapi 开发单页应用程序。我正在尝试从我的网站下载一些 .exe 文件。 我在页面上有一个下载按钮,当用户点击它时,浏览器会提示输入保存的位置,并且 .exe 文件应该下载到他的本地机器上。

请分享你的想法。

谢谢。

哈里克。

【问题讨论】:

标签: angularjs asp.net-web-api typescript


【解决方案1】:

只需创建链接<a href="path_to_exe_file">Download</a>

【讨论】:

    【解决方案2】:

    好吧,晚了 3 年,但在这里发布答案以供将来参考。

    首先,在您的 ASP.NET Web api 控制器中:-

    [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);
        }
    }
    

    如您所见,向客户端发送.exe 文件的方法与发送.txt/.pdf 文件的方法完全相同。您只需要将ContentType更改为正确的类型:applicaion/XXX

    然后您可以使用 HttpClient 从您的 Angular SPA 调用上述 api,或者只需将您的 api 的 url 放在 a 标签的 href 属性内:

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

    点击这个a元素会向上面的url发送一个GET请求,文件就会被下载。

    【讨论】:

      猜你喜欢
      • 2017-01-24
      • 2017-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 2012-11-20
      • 2015-09-17
      相关资源
      最近更新 更多