您好,在我的Angular 2应用中,我正在使用ng2-file-upload:
<input type="file" ng2FileSelect [uploader]="uploader" multiple (change)="onChange($event)">
我想在上传器或事件对象的javascript代码中创建图片对象的实例。不知何故喜欢:
public onChange(event) {
let item = this.uploader.queue[0];
let img = new Image();
img.src = item.SOMETHING;
OR
img.src = event.SOMETHING;
}
我不知道该怎么做。
答案 0 :(得分:5)
你可以在没有任何第三方库的情况下做到这一点。
<强> helloworld.component 强>
import {Component} from 'angular2/core';
@Component({
// Declare the tag name in index.html to where the component attaches
selector: 'hello-world',
// Location of the template for this component
templateUrl: 'src/hello_world.html',
styles: [`
.preview img{
max-height: 50px;
}
`]
})
export class HelloWorld {
// Declaring the variable for binding with initial value
yourName: string = '';
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
var img = document.querySelector("#preview img");
img.file = file;
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
}
}
}
<强>的src / hello_world.html 强>
<div id="preview" class="preview">
<img src="">
</div>
<form>
<input type="file" (change)="fileChange($event)" placeholder="Upload file">
</form>
答案 1 :(得分:1)
你可以这样做 ng2-file-upload还要检查代码
组件代码:
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
import { FileItem } from 'ng2-file-upload';
@Component({
selector: 'app-image',
templateUrl: './image.component.html',
styleUrls : []
})
export class ImageComponent implements OnInit {
public imageUrlPath: SafeUrl;
public uploader: FileUploader;
constructor(private sanitizer: DomSanitizer ){
this.uploader = new FileUploader({
allowedMimeType: [],
maxFileSize: 10 * 1024 * 1024, // 10 MB
});
this.uploader.onAfterAddingFile = (fileItem) => {
fileItem.withCredentials = false;
this.imageUrlPath = this.sanitizer.bypassSecurityTrustUrl((window.URL.createObjectURL(fileItem._file)));
};
}
ngOnInit(){}
}
html代码:
<input type="file" ng2FileSelect [uploader]="uploader">
<div>
<img *ngIf="imageUrlPath" [src] = imageUrlPath>
</div>
点击此链接:image preview,image directive