Being a newbie to Angular 4 and typescript, I am not sure how to receive a memory stream sent back by the API controller and popup a file dialog to save it on the client.
This is what I currently have:
1) in my API controller, I am sending back an HttpResponseMessage such as:
public HttpResponseMessage Post(ReportsManagementUI workobj)
{
var zipfilename = workobj.CreateZipReport(session, sessionuser);
using (MemoryStream ms = new MemoryStream())
{
using (FileStream file = new FileStream(zipfilename, 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", zipfilename);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = zipfilename;
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
}
}
2) in my provider.ts, I have a function createReportsManagement which posts to the API controller code above:
public createReportsManagement(updatetype: string, reportsManagementObj: any) {
reportsManagementObj.actiontype = updatetype;
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var objectToSend = JSON.stringify(reportsManagementObj);
let apiURL = this.framework_virtual_path + "api/ReportsManagement";
return this.http_request.post(apiURL, objectToSend, { headers: headers })
.map(response => response.text())
.catch(this.handleError);
}
3) On my html page, I have a component which calls the provider to create the report zip file.
This is where I am trying to use the KendoUI file-saver method saveAs() to popup the File Save dialog:
import { saveAs, encodeBase64 } from '@progress/kendo-file-saver';
...
private btnExcelClick() {
this.reportsLoading = true;
var responseType = 'arraybuffer';
this.myProvider.createReportsManagement("createReport", this.reportsMgmtObj)
.subscribe(
(response: any) => {
//question !!! is "data:text/plain" OK for zip file content?
const dataURI = "data:text/plain;base64," + encodeBase64(response);
saveAs(dataURI, "test.zip");
//this test code works and downloads the file test.txt
//const dataURI = "data:text/plain;base64," + encodeBase64("HELLO TEST");
//saveAs(dataURI, "test.txt");
} );
}
Thanks for any pointer!