【问题标题】:How to get image and show in my page angular 6如何获取图像并在我的页面中显示 angular 6
【发布时间】:2019-07-30 03:57:35
【问题描述】:

我正在将图像从上传器保存到数据库中,所以它对我来说非常适合,但问题是我是否想在我的网站上显示该图像,那么我该如何显示它们,并且图像路径应该显示为 src="http://www.example.com/image.png"。 请给我任何示例/解决方案。

TS

imageUrl: string = "/assets/img/default-image.png";
  fileToUpload: File = null;
  constructor(private imageService: ImageUploadService) { }

  handleInputFile(file: FileList){
    this.fileToUpload = file.item(0);
    var reader = new FileReader();
    reader.onload = (event:any) => {
      this.imageUrl = event.target.result;
    }
    reader.readAsDataURL(this.fileToUpload);
  }

  OnSubmit(Caption,Image){
    this.imageService.postFile(Caption.value, this.fileToUpload).subscribe(
      data => {
        console.log("Done");
        Caption.value = "";
        Image.value = "";
      }
    );
  }

Service.Ts

postFile(caption: string, fileToUpload: File){
    const endpoint = 'http://localhost:3343/api/UploadImage';
    const formData: FormData = new FormData();
    formData.append("Image", fileToUpload, fileToUpload.name);
    formData.append("Caption", caption);
    return this.http.post(endpoint,formData);
  }

HTML

<form #imageForm="ngForm" (ngSubmit)="OnSubmit(Caption,Image)">
        <div class="input-field col s12">
          <input type="text" #Caption ngModel name="Caption" id="Caption">
          <label for="Caption">Caption</label>
        </div>
        <img [src]="imageUrl" style="width:200px;height:200px;">
        <input type="file" #Image accept="Image/*" (change)="handleInputFile($event.target.files)">
        <button class="btn waves-effect waves-light" type="submit">Submit
          <i class="material-icons right">send</i>
        </button>
      </form>

【问题讨论】:

  • 我在回答中做了一个demo,你可以看看

标签: angular typescript asp.net-web-api file-upload angular6


【解决方案1】:

我正在分享我的项目中的代码。在这个例子中,

我有一个 API,我用 customerNumber 调用它,它返回给我 blob 类型的数据。然后我将这些数据从服务返回到我的组件,在我的组件端,我将该数据作为 blob 并使用 this.createImageFromBlob 函数将其转换为 Image 类型。最后,我通过在&lt;img [src]="imageToShow.photo"&gt; 标记中使用imageToShow.photo 变量在模板端显示该图像。

我的 service.ts 方面,

  getCustomerImages(customerNumber: number, type: string): Observable<File> {
    let result: Observable<any> = this.http
      .get(`${this.apiBaseUrl}csbins/Customer/${customerNumber}/images`, { responseType: "blob" });
    return result;
  }

我的 component.ts 方面,

  getCustomerImages() {
    this.isImageLoading = true;
    this.getCustomerImagesSubscription = this.getCustomerService.getCustomerImages(this.refNo).subscribe(
      data => {
        this.createImageFromBlob(data);
        this.isImageLoading = false;
      },
      error => {
        this.isImageLoading = false;
      });
  }

并在您的组件中将 blob 转换为图像,

  createImageFromBlob(image: Blob) {
    let reader = new FileReader();
    reader.addEventListener("load",
      () => {
          this.imageToShow.photo = reader.result;
      },
      false);

    if (image) {
      if (image.type !== "application/pdf")
        reader.readAsDataURL(image);
    }
  }

还有我的 template.html 方面,

          <ng-template [ngIf]="imageTypeShow">
              <ng-template [ngIf]="imageToShow.photo">
                  <img [src]="imageToShow.photo" class="img-thumbnail" *ngIf="!isImageLoading;">
              </ng-template>
          </ng-template>

如果有不明白的地方可以随时提问。

【讨论】:

    【解决方案2】:

    这是我用来从数据库中读取图像的方式。

    在服务中创建方法以从数据库中获取图像

    getImage(path: string){
            return  this.http.get('/api/image?name=' + encodeURIComponent(path));
    }
    

    在组件中使用服务 在构造函数组件中添加private sanitizer: DomSanitizer

     this.imageService.getImage(this.path).
                    subscribe((data: any) => {
    
                                let objectURL = 'data:image/png;base64,' + data.Image;
                 this.image = this.sanitizer.bypassSecurityTrustUrl(objectURL);
    
                }, (err) => {
                    console.log('HttpErrorResponse error occured.');
                });
    

    在 HTML 文件中显示

    <img id="myimage" [src]='image' >
    

    更新: 我从存储在 json 文件中的 base64 格式创建了一个演示显示图像。 https://stackblitz.com/edit/display-image-from-api

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      相关资源
      最近更新 更多