1

I am trying to open the file available in local drive directly using the angular application with whatever the editor the system is associated with.

Html

<a href="file:///C:/Users/Public/Pictures/Sample%20Pictures/Desert.jpg">  
<span  (click)="openFile(parameter)">Open file</span></a>

I have also tried using the below approach with no help.

window.open("file:///C:/Users/Public/Pictures/Sample%20Pictures/Desert.jpg")

But I am getting the following error message in browser console:

  • Not allowed to access local resource

I understand that we cannot directly access the local drive files directly using the angular application.

Is there any way round to open any type of file(like jpg, docx, txt, etc)?

I know its a common issue and definitely, your answers will help lot of people.

Thanks in advance.

Pearl
  • 8,373
  • 8
  • 40
  • 59
  • 1) Include them in your angular application's assets; or 2) serve the files from a local or remote web server. – Robby Cornelissen Aug 13 '18 at 09:42
  • Host the file on a web server and ajax it. Under normal conditions, jaavscript has no programmatical access to the users hard drive. Imagine what kind of malice could be done if it was possible. – Shilly Aug 13 '18 at 09:43
  • i think you are using chrome may be [chrome local file security issue](https://stackoverflow.com/a/46480984/2417602) will help – vikscool Aug 13 '18 at 09:43
  • Were you able to resolve it? i am stuck in the same issue. – Aarchie Oct 10 '18 at 18:54

3 Answers3

4

you can load files from the client machine using Javascript FileReader object

import { Component } from '@angular/core';

@Component({
  selector: 'app',
  encapsulation: ViewEncapsulation.None,
  template: `<input id="preview" type="file" (change)="previewFile($event)" />`
})
export class AppComponent implements OnInit {
  ...
  public previewImage(event) {
    const reader = new FileReader();
    reader.onload = (e: any) => {
      console.log('csv content', e.target.result);
    };
    reader.readAsDataURL(event.target.files[0]);
  }
}
ImAtWar
  • 1,073
  • 3
  • 11
  • 23
mittal bhatt
  • 955
  • 6
  • 13
0

If you are using chrome then chrome specifically blocks local file access this way for security reasons.

there is a workaround for this that can be found here How to set the allow-file-access-from-files flag option in Google Chrome

Barr J
  • 10,636
  • 1
  • 28
  • 46
0

As the answer of Barr J, it's due to the security reason of Chrome.

I used a simple extension serve server "Web Server for Chrome".

You choose the folder (C:\images) and launch the server on your desired port. Now access your local file by:

function run(){
   var URL = "http://127.0.0.1:8887/image.jpg";    
   window.open(URL, null);    
}
run();
Antoine V
  • 6,998
  • 2
  • 11
  • 34