the goal is to make a http request (empty) from Angular 7 to PHP to receive binary data in Angular for the use with protobuf3. More specifically, the binary data (encoded like described here: https://developers.google.com/protocol-buffers/docs/encoding) in PHP (source) is encapsulated in a string, while the goal in Angular is a Uint8Array.
Therefore, I currently have the following working code:
PHP Code (a simple ProcessWire root template):
header('Content-Type: application/b64-protobuf');
…
echo base64_encode($response->serializeToString());
Angular:
let res = this.httpClient.get(`${this.API_URL}`, { responseType: 'text' });
res.subscribe((data) => {
let binary_string = atob(data);
let len = binary_string.length;
let bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
let parsedResponse = pb.Response.deserializeBinary(bytes)
})
As you can see I encode the data as base64 before sending it. So, it is not as efficient as it could be, because base64 reduces the amount of information per character. I tried already quite a lot to get binary transmission working, but in the end the data always gets corrupted, i.e. the variable bytes is not identical to the argument of base64_encode.
But still, according to some sources (e.g. PHP write binary response, Binary data corrupted from php to AS3 via http (nobody says it would not be possible)) it should be possible.
So my question is: What must change to directly transfer binary data? Is it even possible?
What have I tried?
- using different headers, such as
header('Content-Type:binary/octet-stream;');or using Blob in Angular. - I also tried to remove
base64_encodefrom the PHP Code andatobfrom the Angular Code. The result: the content of the data is modified betweenserializeToStringanddeserializeBinary(bytes), which is not desired. - I checked for possible characters before
<?php
Specifications:
- PHP 7.2.11
- Apache 2.4.35
- Angular 7.0.2
If further information is needed, just let me know in the comments. I am eager to provide it. Thanks.
$response->serializeToString()would be a string, not "binary data."header('Content-Type:binary/octet-stream;');which, combined with echo, should return the string/data as it is. According to the response to stackoverflow.com/questions/11022213/php-write-binary-response strings and byte arrays are the same anyways. In the end a hex analysis showed some additional/changed/removed bytes.