我正在尝试从文件输入控件获取多个文件的方法,并迭代这些文件获取其路径并将它们存储在数组中,在html中,我想在此处显示所有多个文件是我的代码。
pictureschanged(input: any) {
const fileList = input.target.files;
this.testimage = this.sanitization.bypassSecurityTrustResourceUrl(input.target.value) ;
console.log(this.testimage);
if (fileList != undefined) {
this.imageColllection = fileList;
this.imageCount = fileList.length;
let arr = [];
for (let i = 0; i < this.imageColllection.length; i++) {
let file = this.imageColllection[i];
var reader = new FileReader();
reader.onload = this.uploadImage.bind(this);
// (e): void => {
// arr.push(e.target['result']);
// reader.readAsDataURL(file);
// }
}
console.log(this.imageColllection);
// reader.readAsDataURL(input.files[0]);
// var path = (window.URL).createObjectURL(fileList[key]);
// console.log(path);
}
}
我的HTML代码
<div class="form-group">
<label for="" class="control-label col-sm-3">
Upload picture:
</label>
<div class="col-sm-9">
<div class="row">
<div class="col-sm-2" *ngFor="let file of imageColllection">
<div class="picture-holder">
<img [src]="testimage" alt="" class="image-prop">
</div>
</div>
<div class="col-xs-12" [ngClass]="{'col-xs-12':imageCount===0,'col-xs-10':imageCount===1,'col-xs-8':imageCount===2,'col-xs-8':imageCount===3}">
<div class="dropZoneOverlay" (change)="pictureschanged($event)" #imageTemp>
<i class="glyphicon glyphicon-plus">
</i>
<input type="file" multiple accept="image/*" class="control-custom FileUpload">
<!-- <div *ngIf="Pictures.touched && Pictures.invalid">
Please provide only 3 pictures
</div> -->
</div>
</div>
</div>
</div>
</div>
在这里,你看到我能够在picturechanged()
方法中获取文件但是无法获取它们的路径,如果我得到路径角度不会加载它本地因为角度防止本地资源不允许,我怎么能实现功能。需要执行以下任务
1)获取文件路径。
2)将这些路径绑定到image src属性。
答案 0 :(得分:0)
在这里,你如何实现它:
组件:
urls = [];
onSelectFile(event) {
if (event.target.files && event.target.files[0]) {
var filesAmount = event.target.files.length;
for (let i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = (event) => {
console.log(event.target.result);
this.urls.push(event.target.result);
}
reader.readAsDataURL(event.target.files[i]);
}
}
}
模板:
<img *ngFor='let url of urls' [src]="url" height="200"> <br/>
<input type='file' (change)="onSelectFile($event)" multiple>
以下是工作演示的链接:
https://stackblitz.com/edit/angular-multi-file-upload-preview