从URL添加图像

时间:2018-07-13 13:50:40

标签: angular typescript

我一直试图从Typescript的URL输入中显示图像,但只能在javascript中做到。当用户插入图像URL时,将显示预览并能够上传。我为没有更多代码而感到抱歉。

upload.component.html

input type="URL" id="myURL" placeholder="insert image URL here" (change)="onURLinserted($event) ">

          <button type="button"  class="btn btn-dark btninput"  [disabled]="toogleBool" (click)="onUpload()">Upload</button>

upload.component.ts

 onURLinserted(event: any) {

}

1 个答案:

答案 0 :(得分:1)

这是您的答案,Iam使用了两种方式的数据绑定来访问您的图像URL。并且还使用了图像标签中的属性绑定来绑定图像。

HTML文件

<input type="URL" name="myURL" [(ngModel)]="myURL" placeholder="insert image URL here" (change)="onURLinserted() ">

<img [src]="imageToShow" alt="Place image title">

打字稿文件

imageToShow:any;
myURL:any

onURLinserted() {
      this.getImage(myURL).subscribe(data => {
        this.createImageFromBlob(data);
      }, error => {
        console.log("Error occured",error);
      });
}

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

createImageFromBlob(image: Blob) {
   let reader = new FileReader(); //you need file reader for read blob data to base64 image data.
   reader.addEventListener("load", () => {
      this.imageToShow = reader.result; // here is the result you got from reader
   }, false);

   if (image) {
      reader.readAsDataURL(image);
   }
}

有关更多详细信息,请访问此链接。

Getting Image from API in Angular 4?

希望对您的问题有所帮助。

编辑:-

import { Http,ResponseContentType } from '@angular/http';

 constructor(private http: Http){}

   getImage(imageUrl: string): Observable<File> {
            let headers={ responseType: ResponseContentType.Blob }
            return this.http
                .get(imageUrl, headers)
                .map((res: Response) => res.blob());
        }

让我们再试一次,