0

I need help please. I have to download files using angular 2.

In the server side I have the following method

[HttpGet] public HttpResponseMessage Download(int id) { var url = @"\\\\srv\\temp\\201589.zip" var fileInfo = new FileInfo(url); using (MemoryStream ms = new MemoryStream()) { using (FileStream file = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read)) { byte[] bytes = new byte[file.Length]; file.Read(bytes, 0, (int)file.Length); ms.Write(bytes, 0, (int)file.Length); HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); httpResponseMessage.Content = new ByteArrayContent(bytes.ToArray()); httpResponseMessage.Content.Headers.Add("x-filename", fileInfo.FullName); httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileInfo.FullName; httpResponseMessage.StatusCode = HttpStatusCode.OK; return httpResponseMessage; } return null; } } 

what should I do at the client side in order to sownloading the file in the same window, so user will see it at the bottom bar of the browser (not in new window or tab)

 let params = new URLSearchParams(); params.append("id", 1); this.http.get("serverUrl/Download", {search: params}).subscribe((data: any) => {}); 

Thank you

8
  • What happens if you add only <a title="Click to download" href="serverUrl/Download">, without any js code. It is worked for me, my controller returned: var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(myStream) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return result; Commented Jan 31, 2017 at 9:49
  • 1
    Try this <a title="Click to download" href="{{getResourceUrl()}}">, and within angular component create proper url with params, or if you have url as property of object you can use <a title="Click to download" [href]="obj.url"> Commented Jan 31, 2017 at 10:03
  • But the download will be in another tab/window no? Commented Jan 31, 2017 at 10:18
  • In my case it was in the same window Commented Jan 31, 2017 at 10:21
  • in which browser? in my case the download is open in a different tab Commented Jan 31, 2017 at 10:40

1 Answer 1

0

Eventually I created a shared component with hidden iframe that gets src so the file will be downloded...

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.