Home

Haxe - JS Target


Filesystem files to js.html.File

When on node/nwjs:

  1. A field is added to js.html.File which is not included in the externs so there will be no intellisense. The "untyped" keyword will be needed. Here is an example from the CastleDB source code:
function onDragDrop( e : js.html.DragEvent ) {
        e.preventDefault();
        for ( i in 0...e.dataTransfer.files.length ) {
            var file = e.dataTransfer.files[i];
            if (haxe.io.Path.extension(file.name) == "cdb") {
                prefs.curFile = untyped file.path;
                load();
            }
        }
    }

2) Read filepath into js.html.File:

haxe private function getFileObject(filePath: String):js.html.File { if (filePath != null) { var fileContent = sys.io.File.getBytes(filePath); var blob = new js.html.Blob([fileContent.getData()], { type: 'application/octet-stream' }); var file = new js.html.File([blob], Path.withoutDirectory(filePath), { type: Mime.lookup(filePath)}); return file; } return null; }

Turns out that constructiong new File() in the browser does not reliably work with utilities like FileReader.readAsDataURL(). The structure of a constructed File object is completely different than one which comes from a file <input> element for some reason, despite being typed the same.

The solution is to NOT use js.html.File or FileReader if you are pulling from the file system. For things like image loading, encode the Base64 and manually construct the data URI.

Edit

Pub: 27 Aug 2024 01:23 UTC

Edit: 30 Aug 2024 10:38 UTC

Views: 43