Search code examples
javascriptangularbrowser

Name of file saved through angular ui


In my angular application, there is a feature to download a file.

When the user clicks on the file download button, the "save as" window opens up, and the user can then set a name to that file, and save it.

I want to know the name of that file that user set.

I know that the full path can not be retrived as mentioned in this -> Get browser download path with javascript, and i don't need the full path, I just need the file name.

update: I want to know the name of file in the .ts(component) file, and show that name in a label tag in the html file.

Is there any way?


Solution

  • I solved the problem i created by using File System API

    See the below code for reference

    public async buttonClick() {
          try {
            const fileHandle = await this.getNewFileHandle();
            if (fileHandle) {
              console.log("after calling getNewFileHandle()");
              console.log(fileHandle.name);  // Got the filename here
              this.filename = fileHandle.name;
            }
          } catch (error) {
            if (error instanceof DOMException) {
              switch (error.name) {
                case 'NotAllowedError':
                  console.error("Permission was denied.");
                  break;
                case 'AbortError':
                  console.error("The operation was aborted.");
                  break;
                case 'SecurityError':
                  console.error("Security error occurred.");
                  break;
                case 'TypeError':
                  console.error("Invalid options were provided.");
                  break;
                default:
                  console.error("An unknown DOMException occurred:", error);
              }
            } else {
              console.error("An unknown error occurred:", error);
            }
          }
        }
        
        getNewFileHandle() {
          let opts={};
          if ('showSaveFilePicker' in window) {
            opts = {
              types: [
                {
                  description: 'Text file',
                  accept: { 'text/plain': ['.txt'] },
                },
              ],
            };
            return window.showSaveFilePicker(opts);
          }
         else{}
        }