【问题标题】:How to open a file from local drive - Angular 4如何从本地驱动器打开文件 - Angular 4
【发布时间】:2018-08-13 09:40:01
【问题描述】:

我正在尝试使用角度应用程序直接打开本地驱动器中可用的文件,并使用与系统关联的任何编辑器。

HTML

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

我也试过在没有帮助的情况下使用以下方法。

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

但我在浏览器控制台中收到以下错误消息:

  • 不允许访问本地资源

我了解我们无法直接使用 Angular 应用程序直接访问本地驱动器文件。

有什么办法可以打开任何类型的文件(如 jpg、docx、txt 等)?

我知道这是一个常见问题,而且您的回答肯定会帮助很多人。

提前致谢。

【问题讨论】:

  • 1) 将它们包含在您的 Angular 应用程序的资产中;或 2) 从本地或远程 Web 服务器提供文件。
  • 在 Web 服务器上托管文件并对其进行 ajax。在正常情况下,jaavscript 无法以编程方式访问用户硬盘。想象一下,如果可能的话,可以做出什么样的恶意。
  • 我认为您正在使用 chrome 可能是 chrome local file security issue 会有所帮助
  • 你能解决它吗?我陷入了同样的问题。

标签: javascript jquery asp.net angular


【解决方案1】:

您可以使用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]);
  }
}

【讨论】:

    【解决方案2】:

    如果您使用的是 chrome,则出于安全原因,chrome 会专门阻止以这种方式访问​​本地文件。

    有一个解决方法可以在这里找到How to set the allow-file-access-from-files flag option in Google Chrome

    【讨论】:

      【解决方案3】:

      作为 Barr J 的回答,这是由于 Chrome 的安全原因。

      我使用了一个简单的extension 服务服务器“Web Server for Chrome”。

      您选择文件夹 (C:\images) 并在所需端口上启动服务器。 现在通过以下方式访问您的本地文件:

      function run(){
         var URL = "http://127.0.0.1:8887/image.jpg";    
         window.open(URL, null);    
      }
      run();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多