I've written a simple rich text editor and want the user to be able to save and open generated files to their local file system. The behaviour I want to emulate can be seen on https://excalidraw.com/ but I've looked at the MDN file API documents and can't work out how to bring up the OS' save/open modals.
Asked
Active
Viewed 332 times
-1
-
2To open the OS's save/open dialogs, you need a url on your server that with the content-type header set to a type like "application/octet-stream" (this is just one possible mime type) – ControlAltDel Jul 29 '20 at 14:22
3 Answers
1
this is a pretty simple approach, that covers most usecases:
const link = document.createElement('a');
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); // this will work with other data too, not only text
link.setAttribute('download', filename);. // you can define a file name`
Caveats: encodeURIComponent has a size limit, and may be different from browser to browser. In that case you could encode in base64, will make the file larger, but no size limit afaik.
Is your question more about how to use the OS modals?

i.terrible
- 157
- 7
-
Yes I think my question may be more about the OS modal, sorry! I want the user to be able to save their work in a specific folder and overwrite the previous version of the document they're writing. I guess the problem with downloading is that they'll end up with a separate version of the file every time they save, and it'll be in the downloads folder too. – Charlie Jul 29 '20 at 15:29
1
To open a file, you can use an input with type file
<input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg">
To save a file, it depends whether the file is generated client-side or server-side. If it's generated server-side, you can simply provide an url. If it's generated client-side, you can use Blob
and URL.createObjectURL
. You can't save the file directly, but you can provide it as a download link for the user. Here's an example.
Edit: You can suggest a file name via the download attribute of the link

nip
- 1,609
- 10
- 20
-
Thanks for the reply! :) On the example i linked (excalidraw), it seems like you can save the file directly - if you press cmd/ctrl+S, it brings up an OS modal and even pre-selects the custom excalidraw file format – Charlie Jul 29 '20 at 15:26
-
1I've edited the answer regarding the filename. The behavior you're describing (keypress -> open dialog) is probably an event listener that goes to the url of the file. – nip Jul 29 '20 at 15:32
-
Sorry if this is a stupid question, but do I need a url even if the file is generated on the client side? – Charlie Jul 29 '20 at 15:42