[英]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.我正在尝试使用 angular 应用程序和系统关联的任何编辑器直接打开本地驱动器中可用的文件。
Html 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:但是我在浏览器控制台中收到以下错误消息:
I understand that we cannot directly access the local drive files directly using the angular application.我知道我们不能直接使用 angular 应用程序直接访问本地驱动器文件。
Is there any way round to open any type of file(like jpg, docx, txt, etc)?有没有办法打开任何类型的文件(如 jpg、docx、txt 等)?
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
您可以使用
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.如果您使用的是 chrome,那么出于安全原因,chrome 会以这种方式专门阻止本地文件访问。
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有一个解决方法,可以在这里找到如何在 Google Chrome 中设置允许文件访问来自文件标志选项
As the answer of Barr J, it's due to the security reason of Chrome.作为 Barr J 的回答,这是由于 Chrome 的安全原因。
I used a simple extension serve server "Web Server for Chrome".我使用了一个简单的扩展服务服务器“Web Server for Chrome”。
You choose the folder (C:\\images) and launch the server on your desired port.您选择文件夹 (C:\\images) 并在所需端口上启动服务器。 Now access your local file by:
现在通过以下方式访问您的本地文件:
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.