A more flexible DownloadSaver?

When I wanted to generate a zip file as the output from an export operation, I discovered that I couldn’t use the built-in DownloadSaver – but I could tweak its code just a little bit to make it work.

The major problem is that the MIME type “text/html” is hard-coded. I changed that in my variant to look at the downloaded filename’s extension (and falling back to “text/html”).

In my variant, I detect the .zip extension and use the MIME type “application/zip;base64”, which is what the JSZip plugin uses.

I think that you quite easily could get rid of “tm-zip-download” and use “tm-download-file”, if the download saver was a little bit more flexible and smart.

What do you think?

It makes sense to me.

Can you suggest the change in usage? Would there be a mimeType options that defaults to text/html? And maybe an extention option as well? Or something else?

What changes would there be to the call sites?

Hi @cdaven I think this recent GitHub ticket relates to the same problem:

2 Likes

My take on it is that the filename’s extension is enough to set the MIME type:

DownloadSaver2.prototype.getMimeType = function(filename) {
	if (filename.endsWith(".zip")) {
		return "application/zip;base64";
	}
	else {
		return "text/html";
	}
};

But you could of course add a mimeType argument as well, to override this default behaviour.

I also had to make another change, to have the web browser download the Base64-encoded zip file correctly:

if(Blob !== undefined && mimeType.startsWith("text/")) {
	var blob = new Blob([text], {type: mimeType});
	link.setAttribute("href", URL.createObjectURL(blob));
} else {
	link.setAttribute("href","data:"+mimeType+"," + encodeURIComponent(text));
}

It seems at least Chromium doesn’t support downloading Base64-encoded zip files via URL.createObjectURL() hrefs, but it works when using the “data:” format.