[英]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.