简体   繁体   中英

How to open a file from local drive - Angular 4

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM