2

I'm setting up a new angular 7 web application. It is simple application with only one purpose. In my typescript component, I am building a JSON Object. Given that the json object is already set and filled with informations, my goal is to let the user choose the path where to save this json object in the user's harddrive. So I need to create some kind of a directory/path chooser dialog ( like 'save as' dialog in google chrome). how can I do that ?

I have found the following answers in which people say that it's impossible to do in modern browsers. I need to confirm that and try to find another solution: Directory Chooser in HTML page Allow to choose directory using Angular FileSaver.js

I have tried this code: but the probleme was that this import the selected folder with all the files inside it, but what I actually only need is its path.

Sam macchi
  • 41
  • 1
  • 4
  • 1
    "following answers in which people say that it's impossible to do in modern browsers" - why do you think they're incorrect? – duffymo Apr 19 '19 at 14:54
  • 1
    May be some updates took places sinces they posted their questions, I need a practical solution for this. – Sam macchi Apr 19 '19 at 14:56
  • 1
    Updates like giving up on security? You need to reconsider. – duffymo Apr 19 '19 at 14:59
  • 1
    Scroll down in this one: https://stackoverflow.com/questions/46470453/angular-2-angular-4-how-can-i-access-file-from-the-local-system-location – duffymo Apr 19 '19 at 15:00
  • There now seems to be an implementation of a directory picker, but it's browser support is limited and requires to run in https context https://developer.mozilla.org/en-US/docs/Web/API/Window/showDirectoryPicker – Jnr Feb 10 '23 at 05:15

2 Answers2

1

It is nothing about Angular, it is the security mechanism of modern browsers, basically browser doesn't allow website access local filesystem, which means you can't choose local folder path by client-side javascript.

The best thing you can do is saving the json objects to browser default download folder

const element = document.createElement('a');
element.setAttribute('href', `data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(jsonObject))}`);
element.setAttribute('download', filename);

document.body.appendChild(element);

element.click();

document.body.removeChild(element);
MarkoCen
  • 2,189
  • 13
  • 24
0

you can save your file as a Blob and use this code

window.navigator.msSaveOrOpenBlob(blob, 'nameOfFile.json');
nircraft
  • 8,242
  • 5
  • 30
  • 46