我对打字稿和网页开发很新,所以如果我的代码很糟糕,我很抱歉.无论如何,我在显示配置文件图片上传的“预览图像”时遇到问题.我正在使用ng2-file-upload将我的图像上传到服务器,该部分工作正常.在我点击上传按钮之前,我想在选择后立即在页面上显示所选图像.目前我试图通过从
HTML
ImageElement检索src属性来显示图像,但src属性似乎是空的.
import { Component,OnInit } from '@angular/core'; import { FileUploader } from 'ng2-file-upload/ng2-file-upload'; const URL = 'http://localhost:4200/api/upload'; @Component({ selector: 'app-view-profile',templateUrl: './view-profile.component.html',styleUrls: ['./view-profile.component.css'] }) export class ViewProfileComponent implements OnInit { constructor() { } public uploader: FileUploader = new FileUploader({url: URL,itemAlias: 'newProfilePicture'}); title: string; previewImage: any; tempImage: any; source: string; imagePreview(input) { document.getElementById("previewImage").style.display="block"; console.log("Image is selected") this.previewImage = document.getElementById("previewImage"); console.log(this.previewImage); this.source = (<HTMLImageElement>document.getElementById('previewImage')).src console.log("Image Source: " + this.source + " Should be inbetween here"); //var reader = new FileReader(); //console.log(this.previewImage); } ngOnInit() { this.title = 'View or Update Your Profile'; this.uploader.onAfterAddingFile = (file)=> {file.withCredentials = false;}; this.uploader.onCompleteItem = (item:any,response:any,status:any,headers:any) => { console.log("ImageUpload:uploaded:",item,status,response); //this.imagePreview(); }; } }
这是我的HTML
<div class="container"> <h1>{{title}}</h1> <div> <input type="file" id="previewImage" (change)="imagePreview(this);" name="newProfilePicture" ng2FileSelect [uploader] ="uploader" /> <button type="button" class="btn btn-success btn-s" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length"> Upload Your File </button> </div> </div>
解决方法
你通过这个简单的功能实现了这个目标:
模板:
<img [src]="url" height="200"> <br/> <input type='file' (change)="onSelectFile($event)">
零件 :
onSelectFile(event) { // called each time file input changes if (event.target.files && event.target.files[0]) { var reader = new FileReader(); reader.readAsDataURL(event.target.files[0]); // read file as data url reader.onload = (event) => { // called once readAsDataURL is completed this.url = event.target.result; } } }
以下是它的工作示例,请查看以下内容: