@@ -664,6 +664,36 @@ with open("data.csv") as f:
664664 data = f.read()
665665```
666666
667+ It's also possible to manually upload files onto the virtual file system
668+ from the browser (<input type =" file " >), and using the DOM API.
669+
670+ The following fragment is just one way to achieve this:
671+
672+ ``` python
673+ # Assume an input element of type "file" with an id of "upload" in
674+ # the DOM.
675+ # E.g. <input type="file" id="upload">
676+
677+ from pyscript import when, fetch, window
678+
679+
680+ @when (" change" , " #upload" )
681+ async def on_change (event ):
682+ """
683+ Activated when the user has selected a file to upload via
684+ the file input element.
685+ """
686+ # For each file the user has selected to upload...
687+ for file in input .files:
688+ # Create a temporary URL.
689+ tmp = window.URL .createObjectURL(file )
690+ # Fetch and save its content somewhere.
691+ with open (f " ./ { file .name} " , " wb" ) as dest:
692+ dest.write(await fetch(tmp).bytearray())
693+ # Then revoke the tmp URL.
694+ window.URL .revokeObjectURL(tmp)
695+ ```
696+
667697#### Writing files
668698
669699You can create and write files in the virtual filesystem:
@@ -684,14 +714,16 @@ def download_file(filename, content):
684714 """
685715 Trigger browser download of file content.
686716 """
717+ # Ensure you use the correct mime-type!
687718 blob = window.Blob.new([content], ffi.to_js({" type" : " text/plain" }))
719+ # Create a temporary download link/URL.
688720 url = window.URL .createObjectURL(blob)
689-
690721 link = window.document.createElement(" a" )
691722 link.href = url
692723 link.download = filename
724+ # Activate the link (pretend to click it).
693725 link.click()
694-
726+ # Then revoke the temporary URL.
695727 window.URL .revokeObjectURL(url)
696728
697729
0 commit comments