[英]Browse file in AngularJS + TypeScript on button click
我有user.component.html和user.component.ts我發現的所有示例都是html格式的<input type="file" />
我不想使用這種樣式。 我的html文件中有:
<button type="button" class="btn" (click)="openPicture()" Browse </button>
以下是ts文件的功能:
public openPicture() {
//for testing
console.log('button clicked to open picture');
var picture = browse.the.picture.and.assing.to.this.variable;
//another test, see on console if picture is read
console.log('%c ', 'font-size: 100px; background: {{picture}} no-repeat;');
// Later display picture variable on html and save to database or do anything desired.
}
我已經找到了關於用angular/material
進行stackoverflow的示例 ,但是我沒有此模塊。 是否有其他替代方法,而無需安裝任何額外的軟件包來解決此問題?
你可以這樣實現
<input type="file" style="display: none" #file (change)="fileChange($event)"/>
<button type="button" class="btn" (click)="file.click()"> Browse </button>
.ts
export class AppComponent {
file: File;
constructor() {
}
fileChange(file) {
this.file = file.target.files[0];
console.log(this.file.name);
}
}
您可以在標簽中嘗試舊的隱藏輸入:
<label class="btn">
Browse <input type="file" style="display: none;" (change)="handleChange($event)">
</label>
handleChange
實現必須消耗事件:
handleChange(event) {
// consume event.target.files[0] which has File type
}
關於File
其余部分可以在MDN上找到
由於瀏覽器的安全功能,實際上需要使用input
標簽來訪問文件系統。 但是,您可以做的就是隱藏input
元素,並從其余的代碼和標記中訪問它。
看看這個相關的答案,以了解您可以做什么。 否則,這是一個如何工作的簡單示例:
<input type="file" style="display: none" #file/>
<button type="button" class="btn" (click)="file.click()" Browse </button
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.