[英]How to download .exe files from SPA using angularjs webapi
我正在使用 angular typescript 和 webapi 開發單頁應用程序。 我正在嘗試從我的網站下載一些 .exe 文件。 我在頁面上有一個下載按鈕,當用戶點擊它時,瀏覽應該提示保存的位置,並且 .exe 文件應該下載到他的本地機器上。
請分享您的想法。
謝謝。
哈里克。
只需創建鏈接<a href="path_to_exe_file">Download</a>
好吧,晚了 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
。
然后,您可以從您的角度SPA使用的HttpClient調用上述API或只是把你的API的URL內href
的屬性, a
標簽:
<a href="http://localhost:XXXXX/url/to/downloadFile">Download</a>
單擊此a
元素將向上述 url 發送 GET 請求並下載文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.