I need to serialize some blobs to send to php. I also want to be able to unserialize it when the php script sends it back. JSON does not stringify the contents of the blob, just metadata like the name, size, etc. How can I do this?
1 Answer
To send multiple Blobs, you can append() them to a FormData instance that you can then .send() with an XMLHttpRequest.
var xhr = new XMLHttpRequest();
var form = new FormData();
form.append('field-name', blob1);
form.append('field-name', blob2, 'filename.ext');
// ...
xhr.send(form);
To receive a Blob, you can set the responseType and get the response.
xhr.responseType = 'blob';
xhr.onload = function () {
var blob = xhr.response;
};
For more info, have a look at MDN's "Sending and Receiving Binary Data."
Also note that all of this requires XMLHttpRequest Level 2.
4 Comments
markasoftware
How can the blob be sent back to the client?
Jonathan Lonowski
@Markasoftware "PHP write binary response" should be able to help with the server-side portion. And, I've included details for receiving
Blobs client-side.markasoftware
ok. Thanks! I would still prefer a way to stringify the blob instead of transmitting it directly, but this is fine.
markasoftware
Thanks, this mostly solves my problem. However, what if I wanted to transmit more than one blob from server to client at once? I understand that I can do this from client to server easily with the formdata thing, but I would also like to do this from server to client.