Multipart download in Angular
We’ll be looking at how to write a client side multipart download code in angular 5. If you do not know what multipart download is , please do checkout my previous write up multipart-download.
This comes in handy if you are scripting a client side web application that needs to download a couple of objects that a pretty big in size. In my case, they were images of the range 5–15 mb. Which is pretty huge. It also helps you use your entire allocated bandwidth (uses all the allocated browser threads).
Writing a Service
Create a service , say file-download.
ng generate service file-download
It gets auto imported to your app.module.ts, but do make sure, and also include in the providers array.
import {MultipartService} from ‘./download-file.service’;
@NgModule({
providers: [MultipartService]
bootstrap: [AppComponent]
})
export class AppModule { }
Now switch over to our service.
Time to write our method.

First we are declaring variables fileSize and assigning it the value of the file we want to download. Don’t forget to initialize a variable url and pass the url in it.
We figure out the chunksize (bytes) by dividing the fileSize by the number of parallel download requests we need, in this case 5.
We iterate over the number of chunks and store the corresponding start and end values of each chunk in json object ‘chunks’.
Now we have to a set a HTTP header ‘range’ and pass in the byte ranges. So we append ‘Range, rangeval’ , where rangeval is a string that contains bytes=start-end, where start and end are numbers taken from the json object.
We are using the httpClientModule to take care of our http communication. So dont forget to import that in your service and in your module.
we append the url and set httpheaders in the headers parameter of http get and push into an array headers.
Firing the Requests
import { forkJoin } from ‘rxjs/observable/forkJoin’;

forkjoin is an operator from the rxjs library. It helps execute observables at once and emit their final values.
We are using it here to fire our http requests, that downloads our file chunk by chunk. Forkjoin, pieces back the chunks (or blobs) and emits one final blob.
We subscribe to it to acquire the final blob. We are using a module file-saver
import { saveAs } from ‘file-saver/FileSaver’;
to save our blob to our file system in the desired format.
We’re invoking a method saveToFileSystem that does this for us. We pass in the entire blob as a parameter.

The header content-disposition would be available to you only if the CORS allow header : content-disposition is set on the server side. You might be able to view it in your browser, but if the header is not set, the browser does not let your application access it. (I know, CORS is a pain in the b.)
So that’s it. It’s a wrap guys.