Skip to content

Instantly share code, notes, and snippets.

@JPVenson
Created December 15, 2019 13:25
Show Gist options
  • Save JPVenson/8eb2686b2f07d28014d0f4098d0e04c4 to your computer and use it in GitHub Desktop.
Save JPVenson/8eb2686b2f07d28014d0f4098d0e04c4 to your computer and use it in GitHub Desktop.
//CS Blazor WebAssembly Part:
public static class FileUtil
{
public static IEnumerable<List<T>> Partition<T>(this IList<T> source, Int32 size)
{
for (int i = 0; i < Math.Ceiling(source.Count / (Double) size); i++)
{
yield return new List<T>(source.Skip(size * i).Take(size));
}
}
public static async ValueTask SaveAs(this IJSRuntime js, string filename, byte[] data)
{
var key = Guid.NewGuid().ToString();
foreach (var partFile in Partition(data, 3125000))
{
await js.InvokeVoidAsync(
"saveAsFileAddBuffer",
key,
partFile);
}
await js.InvokeVoidAsync(
"saveBuffer",
filename,
key);
}
}
//js Part:
_buffer = new Array();
function saveAsFileAddBuffer(key, bytesBase64) {
var filter = _buffer.filter(e => e.Key == key);
if (filter.length === 0) {
filter = {
Key: key,
Buffer: new Array()
};
_buffer.push(filter);
} else {
filter = filter[0];
}
filter.Buffer.push(bytesBase64);
}
function saveBuffer(filename, key) {
console.log("Save " + key);
var filter = _buffer.filter(e => e.Key == key)[0];
var parts = new Array();
for (var base64Part in filter.Buffer) {
var bytes = new Uint8Array(base64Part.length);
for (var i = 0; i < base64Part.length; i++) {
bytes[i] = base64Part.charCodeAt(i);
}
parts.push(bytes);
}
_buffer.splice(_buffer.indexOf(filter), 1);
var blob = new Blob(parts, { type: "application/octet-stream" });
if (navigator.msSaveBlob) {
//Download document in Edge browser
navigator.msSaveBlob(blob, filename);
}
else {
var link = document.createElement('a');
link.download = filename;
link.href = URL.createObjectURL(blob);
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment