Skip to content

Commit

Permalink
FileReference: download() html5 improvements
Browse files Browse the repository at this point in the history
If we allow the download method to be exposed on html5, it should at least do something. This change makes it work minimally even though we can not open a file dialog on all browsers yet. 

Chromes File API is slowly being adopted, so we may be able to support this better in the future.
  • Loading branch information
Dimensionscape committed Apr 25, 2024
1 parent c7861ad commit 34c8fb1
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions src/openfl/net/FileReference.hx
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,8 @@ class FileReference extends EventDispatcher
@:noCompletion private var __urlLoader:URLLoader;
#if (js && html5)
@:noCompletion private var __inputControl:InputElement;
@:noCompletion private var __pendingDownload:Bool = false;
@:noCompletion private var __pendingDefaultFileName:Null<String>;
#end

/**
Expand Down Expand Up @@ -853,6 +855,11 @@ class FileReference extends EventDispatcher
saveFileDialog.onSelect.add(saveFileDialog_onSelect);
saveFileDialog.browse(SAVE, defaultFileName != null ? Path.extension(defaultFileName) : null, defaultFileName);
#end

#if(js && html5)
__pendingDownload = true;
__pendingDefaultFileName = defaultFileName;
#end
}

/**
Expand Down Expand Up @@ -1469,7 +1476,6 @@ class FileReference extends EventDispatcher

@:noCompletion private function urlLoader_download_onComplete(event:Event):Void
{
#if (desktop && sys)
if ((__urlLoader.data is ByteArrayData))
{
__data = __urlLoader.data;
Expand All @@ -1479,7 +1485,8 @@ class FileReference extends EventDispatcher
__data = new ByteArray();
__data.writeUTFBytes(Std.string(__urlLoader.data));
}


#if (desktop && sys)
if (__path != null)
{
File.saveBytes(__path, __data);
Expand All @@ -1489,6 +1496,18 @@ class FileReference extends EventDispatcher
}
#end

#if(js && html5)
#if(lime && !macro)
if(__pendingDownload){
//Maybe just use an achor element and save the data as a blob with js instead of invoking lime?
var saveFileDialog = new FileDialog();
saveFileDialog.save(__data, __pendingDefaultFileName != null ? Path.extension(__pendingDefaultFileName) : null, __pendingDefaultFileName);
__pendingDownload = false;
__pendingDefaultFileName = null;
}
#end
#end

dispatchEvent(event);
}

Expand Down Expand Up @@ -1520,6 +1539,13 @@ class FileReference extends EventDispatcher

@:noCompletion private function urlLoader_onIOError(event:IOErrorEvent):Void
{
#if(js && html5)
if(__pendingDownload){
__pendingDownload = false;
__pendingDefaultFileName = null;
}
#end

dispatchEvent(event);
}

Expand Down

0 comments on commit 34c8fb1

Please sign in to comment.