Skip to content

Commit 8cabee9

Browse files
Add ability for WebGL to download from a segement of a byte array (#2)
Useful for grabbing the correct segment of a buffer, like in a MemoryStream. Avoids using ToArray on the C# end, which makes a copy.
1 parent b9905df commit 8cabee9

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

StandaloneFileBrowser/Plugins/StandaloneFileBrowser.jslib

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,39 @@ var StandaloneFileBrowserWebGLPlugin = {
5454
}
5555
},
5656

57+
// Save file from span of bytes
58+
// DownloadFile method does not open SaveFileDialog like standalone builds, its just allows user to download file
59+
// gameObjectNamePtr: Unique GameObject name. Required for calling back unity with SendMessage.
60+
// methodNamePtr: Callback method name on given GameObject.
61+
// filenamePtr: Filename with extension
62+
// byteArray: byte[] to pull a span from
63+
// byteSpanStart: start index of span
64+
// byteSpanSize: length of span
65+
DownloadFileSpan: function(gameObjectNamePtr, methodNamePtr, filenamePtr, byteArray, byteSpanStart, byteSpanSize) {
66+
gameObjectName = UTF8ToString(gameObjectNamePtr);
67+
methodName = UTF8ToString(methodNamePtr);
68+
filename = UTF8ToString(filenamePtr);
69+
70+
var bytes = new Uint8Array(byteSpanSize);
71+
for (var i = 0; i < byteSpanSize; i++) {
72+
bytes[i] = HEAPU8[byteArray + byteSpanStart + i];
73+
}
74+
75+
var downloader = window.document.createElement('a');
76+
downloader.setAttribute('id', gameObjectName);
77+
downloader.href = window.URL.createObjectURL(new Blob([bytes], { type: 'application/octet-stream' }));
78+
downloader.download = filename;
79+
document.body.appendChild(downloader);
80+
81+
document.onmouseup = function() {
82+
downloader.click();
83+
document.body.removeChild(downloader);
84+
document.onmouseup = null;
85+
86+
SendMessage(gameObjectName, methodName);
87+
}
88+
},
89+
5790
// Save file
5891
// DownloadFile method does not open SaveFileDialog like standalone builds, its just allows user to download file
5992
// gameObjectNamePtr: Unique GameObject name. Required for calling back unity with SendMessage.

0 commit comments

Comments
 (0)