[英]How to open a file from local drive - Angular 4
我正在尝试使用 angular 应用程序和系统关联的任何编辑器直接打开本地驱动器中可用的文件。
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 等)?
我知道这是一个常见问题,而且您的回答肯定会帮助很多人。
提前致谢。
您可以使用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]);
}
}
如果您使用的是 chrome,那么出于安全原因,chrome 会以这种方式专门阻止本地文件访问。
有一个解决方法,可以在这里找到如何在 Google Chrome 中设置允许文件访问来自文件标志选项
作为 Barr J 的回答,这是由于 Chrome 的安全原因。
我使用了一个简单的扩展服务服务器“Web Server for Chrome”。
您选择文件夹 (C:\\images) 并在所需端口上启动服务器。 现在通过以下方式访问您的本地文件:
function run(){
var URL = "http://127.0.0.1:8887/image.jpg";
window.open(URL, null);
}
run();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.