[英]Angular 2: get image from file upload
Hi in my Angular 2 app I am using ng2-file-upload: 嗨,在我的Angular 2应用程序中,我正在使用ng2-file-upload:
<input type="file" ng2FileSelect [uploader]="uploader" multiple (change)="onChange($event)">
I would like to create an instance of image object in my javascript code from uploader or the event object. 我想在我的javascript代码中从uploader或event对象创建一个image对象的实例。 Somehow like:
不知何故喜欢:
public onChange(event) {
let item = this.uploader.queue[0];
let img = new Image();
img.src = item.SOMETHING;
OR
img.src = event.SOMETHING;
}
I am not sure how to do that. 我不知道该怎么做。
You can do that without any third-party library. 你可以在没有任何第三方库的情况下做到这一点。
helloworld.component 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 SRC / hello_world.html
<div id="preview" class="preview">
<img src="">
</div>
<form>
<input type="file" (change)="fileChange($event)" placeholder="Upload file">
</form>
You can do this with ng2-file-upload also.check below code 您也可以使用ng2-file-upload执行此操作。 请检查以下代码
component code: 组件代码:
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 code: HTML代码:
<input type="file" ng2FileSelect [uploader]="uploader">
<div>
<img *ngIf="imageUrlPath" [src] = imageUrlPath>
</div>
follow this link: image preview , image directive 点击此链接: 图像预览 , 图像指令
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.