Sam macchi
Sam macchi

Reputation: 41

How to build a directory chooser in an angular 7 application?

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.

Upvotes: 2

Views: 4204

Answers (2)

Thomas Gicquel
Thomas Gicquel

Reputation: 71

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

window.navigator.msSaveOrOpenBlob(blob, 'nameOfFile.json');

Upvotes: 0

MarkoCen
MarkoCen

Reputation: 2324

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);

Upvotes: 1

Related Questions