Download file in Angular2

Download file using Angular2.

Download file in Angular2 from server.

In this post, we will see how to download binary file from server using AngularJS and HTTP protocol.
 
Download binary file in angularjs using http
Download binary file in angularjs using HTTP

Many a times we need to download file from server via HTTP call, In this post we will see how to download file in Angular2 using GET/POST request from server.

Example demonstrates downloading binary file using Angular2 and REST service.

Note: In this example, we are downloading sample csv file from server, but you can download any file like pdf, excel, zip etc, just make sure to put correct  media type like "text/csv" for csv etc.

Below method is used to download file in Angular2.


downloadSampleCSVFiles() {
 var nameOfFileToDownload = "SampleFileToDownload.csv";
 var result = this.downloadSampleCSV(nameOfFileToDownload);
 result.subscribe(
  success => {
   var blob = new Blob([success._body], { type: 'text/csv' });

   if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, nameOfFileToDownload);
   } else {
    var a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = nameOfFileToDownload;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
   }
  },
  err => {
   alert("Server error while downloading file.");
  }
 );
}


downloadSampleCSV(fileNameToDownload) {
 return this._http.post("scheduler/downloadSampleCSV", fileNameToDownload, this.options);
}

Complete Example- Client code


download.component.html
<a class="btn btn-primary" (click)="downloadSampleCSVFiles()">
    Download File
</a>

download.component.ts
import { Component } from "@angular/core";
import { Observable, Subscription } from 'rxjs/Rx';
import { Http, Response, Headers, RequestOptions, RequestMethod, RequestOptionsArgs, URLSearchParams } from '@angular/http';
import { Subject } from 'rxjs/Rx';

@Component({
    template: require('./download.component.html')
})

export class DownloadComponent {

    private options = new RequestOptions(
        { headers: new Headers({ 'Content-Type': 'application/json' }) });

    constructor(
        private _http: Http) {
    }

    downloadSampleCSVFiles() {
        var nameOfFileToDownload = "SampleFileToDownload.csv";
        var result = this.downloadSampleCSV(nameOfFileToDownload);
        result.subscribe(
            success => {
                var blob = new Blob([success._body], { type: 'text/csv' });

                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveOrOpenBlob(blob, nameOfFileToDownload);
                } else {
                    var a = document.createElement('a');
                    a.href = URL.createObjectURL(blob);
                    a.download = nameOfFileToDownload;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                }
            },
            err => {
                alert("Server error while downloading file.");
            }
        );
    }

    downloadSampleCSV(fileNameToDownload) {
        return this._http.post("scheduler/downloadSampleCSV", fileNameToDownload, this.options);
    }
}

Java REST service.


DownloadController.java
package com.javabypatel.demo;

import java.io.IOException;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/download/")
public class DownloadController {

 @RequestMapping(method = RequestMethod.POST, value = "downloadSampleCSV")
 public ResponseEntity<?> downloadSampleCSV(@RequestBody String fileName) {
  System.out.println("Request received to download sample .csv file");
  System.out.println("File to download :"+fileName);
  Resource resource = new ClassPathResource("/Customers.csv");
  byte[] content = null;
  try {
   content = FileCopyUtils.copyToByteArray(resource.getInputStream());
   System.out.println("Converted .csv to bytes successfully.");
  } catch (IOException e1) {
   System.err.println("Error while converting file to bytes.");
   e1.printStackTrace();
  }

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.parseMediaType("text/csv"));
  System.out.println("Download sample .csv request completed");
  return new ResponseEntity<byte[]>(content, headers, HttpStatus.OK);
 }

}

You may also like to see


Implement Stack using One Queue


Find Largest and Smallest number in Array

Count zeros in a row wise and column wise sorted matrix

Find middle element of a linked list

Union and Intersection of Two Sorted Arrays

Merge two sorted arrays in Java

How is ambiguous overloaded method call resolved in java


Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Post a Comment