Skip to content

Instantly share code, notes, and snippets.

@dennis-8
Created August 28, 2018 11:05
Show Gist options
  • Save dennis-8/29572e8acbe82cee6834bb1236b23581 to your computer and use it in GitHub Desktop.
Save dennis-8/29572e8acbe82cee6834bb1236b23581 to your computer and use it in GitHub Desktop.
Ajax file download
https://github.com/eligrey/FileSaver.js/
@dennis-8
Copy link
Author

dennis-8 commented Aug 28, 2018

Download file(s) with Ajax as {byte[], fileName}.

var endpoint = 'api/files/getall';

return getById(id, endpoint)
	.then(function (result) {

		var files = result.data;
		if (!files) {
			return;
		}

		for (var i = 0; i < files.length; i++) {
			var file = files[i];

			var blob = b64toBlob(file.Bytes);
			saveAs(blob, file.FileName);
		}
	})
	.catch(function () {
		alert('Error downloading files.');
	});

b64toBlob function:

function b64toBlob(b64Data, contentType, sliceSize) {
	contentType = contentType || '';
	sliceSize = sliceSize || 512;

	var byteCharacters = atob(b64Data);
	var byteArrays = [];

	for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
		var slice = byteCharacters.slice(offset, offset + sliceSize);

		var byteNumbers = new Array(slice.length);
		for (var i = 0; i < slice.length; i++) {
			byteNumbers[i] = slice.charCodeAt(i);
		}

		var byteArray = new Uint8Array(byteNumbers);

		byteArrays.push(byteArray);
	}

	var blob = new Blob(byteArrays, { type: contentType });
	return blob;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment