[英]How to get interim response in 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。 請幫助我如何獲得臨時答復。
您提到可以控制用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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.