Angular2文件输入onchange [英] Angular2 file input onchange
问题描述
我点击选择文件 - >选择文件 - >现在系统检测到变化并调用一些打印所有这些文件信息的函数(例如图像名称)。
我不能在输入文件上使用ngModel,对不对?如何做到这一点?
使用下面的模板:
< pre class =lang-html prettyprint-override> < div class =modal-body>
< input type =file(change)=fileChangeEvent($ event)placeholder =上传文件.../>
< img id =previewsrc =alt =预览>
< / div>
然后你的Component fileChangeEvent()
/ file>
public fileChangeEvent(fileInput:any){
if(fileInput.target.files& amp; ;& fileInput.target.files [0]){
var reader = new FileReader();
reader.onload = function(e:any){
$('#preview')。attr('src',e.target.result);
}
reader.readAsDataURL(fileInput.target.files [0]);
$ b $ p
$ b $ p $所有文件相关的信息将控制台....
I have input file (without submit - typicall input file). I'd like to call some function when chose file.
Example:
I click on "Choose file" -> choose file -> now system detects change and call some function which prints all these file information (for example image name).
I can't use ngModel on input file, right? How to do that?
解决方案 Use the following in your template:
<div class="modal-body">
<input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
<img id="preview" src="" alt="Preview">
</div>
Then your Component fileChangeEvent()
as
public fileChangeEvent(fileInput: any){
if (fileInput.target.files && fileInput.target.files[0]) {
var reader = new FileReader();
reader.onload = function (e : any) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(fileInput.target.files[0]);
}
}
All Your File related info will console....
这篇关于Angular2文件输入onchange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!