Redo Zotero.File.generateDataURI() without XPCOM and type sniffing

Now async and takes a contentType parameter
This commit is contained in:
Dan Stillman 2021-01-20 06:35:52 -05:00
parent c13ac32ad2
commit 2a203afb20

View file

@ -778,23 +778,25 @@ Zotero.File = new function(){
/** /**
* Generate a data: URI from an nsIFile * Generate a data: URI from a file path
* *
* From https://developer.mozilla.org/en-US/docs/data_URIs * @param {String} path
* @param {String} contentType
*/ */
this.generateDataURI = function (file) { this.generateDataURI = async function (file, contentType) {
var contentType = Components.classes["@mozilla.org/mime;1"] if (!contentType) {
.getService(Components.interfaces.nsIMIMEService) throw new Error("contentType not provided");
.getTypeFromFile(file); }
var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream); var buf = await OS.File.read(file, {});
inputStream.init(file, 0x01, 0o600, 0); var bytes = new Uint8Array(buf);
var stream = Components.classes["@mozilla.org/binaryinputstream;1"] var binary = '';
.createInstance(Components.interfaces.nsIBinaryInputStream); var len = bytes.byteLength;
stream.setInputStream(inputStream); for (let i = 0; i < len; i++) {
var encoded = btoa(stream.readBytes(stream.available())); binary += String.fromCharCode(bytes[i]);
return "data:" + contentType + ";base64," + encoded; }
} return 'data:' + contentType + ';base64,' + btoa(binary);
};
this.setNormalFilePermissions = function (file) { this.setNormalFilePermissions = function (file) {