How to implement Save and Save As without download using Javascript?

Viewed 528

I'm developing a web application that kind of resembles a graph editor, which lets users insert boxes, draw connections, etc.

When trying to implement the Save and Save As feature, I stuck at how to save the files locally. I've tried creating a tags with download attribute, then triggering their click events, but it doesn't allow renaming and choosing the directory. Instead, every time the user hits Save, it starts a new download, resulting in numerous duplicates in the Downloads folder.

function downloadFile(myFileName, myContent) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(myContent));
    pom.setAttribute('download', myFileName);
    pom.click();
}

How I want it to work is like, for example, diagrams.net. When creating a new file using Device storage, it first launches the Save As box asking for name and directory. Afterward, when hitting Save, the already created file gets overwritten instead of downloading another version of the file.

What should I do to achieve this using Javascript?

1 Answers

diagrams.net does this using the quite new and experimental File System Access API. That is only supported in Chrome Edge and Opera as of Feb. 2021

It provides the function showSaveFilePicker, here is an example on how to use it.

if("showSaveFilePicker" in window) {
  try {
    const file = window.showSaveFilePicker({
      types: [
        {
          description: "An XML File",
          accept: {"text/xml": [".xml"]}
        },
        {
          description: "A Text File",
          accept: {"text/plain": [".txt", ".text"]}
        }
      ]
    })
  } catch (e) {
    console.error(e)
  }
} else {
  alert("Your Browser does not support the FSA API")
  // use <a download></a> fallback
}

Note that I cannot add an executable code snippet because sandboxed scripts e.g.: in an IFrame are not allowed to show the file picker.

Related