如何在Angular HTTP中获得临时响应-ArrayBuffer

时间:2019-01-25 06:10:03

标签: angular electron httpresponse angular-http arraybuffer

我内部有一个Electron应用程序,我正在加载Angular应用程序。我正在通过API调用下载字节数组(即ArrayBuffer),并将这些数据传递给我通过electron.remote.require('./ file-service')连接以在本地创建文件的方法文件系统。

如果用户更改了路线,则会弹出一个窗口提示您确认导航。如果用户单击“确定”并且http请求介于两者之间,则我需要存储接收到的字节。

示例角度代码:

declare var electron: any;
const { createDataFile } = electron.remote.require('./file-service')

const payLoad = new FormData();
const httpOptions =  {
      headers: new HttpHeaders(),
      reportProgress: true,
    };

const req = new HttpRequest('GET', 'http://localhost:8080/getData', payLoad, {...httpOptions, responseType: 'arraybuffer'});
this.http.request<ArrayBuffer>(req).subscribe((event: HttpEvent<ArrayBuffer>) => {

    switch (event.type) {
        case HttpEventType.DownloadProgress:
            // This method will manipulate and show the progress bar in the UI
            this.updateProgress(event.loaded);
        break;
        case HttpEventType.Response:
            createDataFile(event.body)
        break;
    }

});

我正在尝试保存数据,如果arraybuffer的大小为25MB,而我却收到了12MB,而我又试图导航,那一刻我需要存储12MB。 请协助我获得临时答复。

1 个答案:

答案 0 :(得分:0)

您提到可以控制用Java编写的后端代码。我不确定是否可以将responseType设置为文本并将编码的字节数组作为字符串发送。但是如果可以的话,您可以从接收到的事件中获取partialText中的临时数据以对其进行解码和存储。

     interface HttpDownloadProgressEvent extends HttpProgressEvent {
      type: HttpEventType.DownloadProgress
      partialText?: string  //The partial response body as downloaded so far.Only present if the responseType was text.

      // inherited from common/http/HttpProgressEvent
      type: HttpEventType.DownloadProgress | HttpEventType.UploadProgress
      loaded: number
      total?: number
    }

    switch (event.type) {
        case HttpEventType.DownloadProgress:
            // This method will manipulate and show the progress bar in the UI
            this.updateProgress(event.loaded);
//////////////////////////////////////////////////////////////////////////////
            store event.partialText; 
/////////////////////////////////////////////////////////////////
        break;
        case HttpEventType.Response:
            createDataFile(event.body)
        break;
    }

别忘了requestProgress

const req = new HttpRequest('POST', 'upload/file', file, {
  requestProgress: true
});