首页 > 解决方案 > 从spring boot中读取字节数组到角度并在新页面上显示内容

问题描述

我正在尝试从 springboot 应用程序中读取字节数组。springboot 应用程序返回一个项目列表,其中包含一个名为:file_item的 json 字段,其中包含相应 blob 的字节数组值。我的目标是在单击相关下载按钮后必须让文件出现在新窗口中。

目前,我收到无法访问该站点的错误消息。

来自后端的 JSON 响应:

[{
    "uid": 1,
    "description_text": "json file for cars",
    "version_number": "1.0",
    "mime_type": "json",
    "file_item": "W3sNCiJtYWtlIjogIkZvcmQiLCANCiJtb2RlbCI6ICJQaW50byIsDQoieWVhciI6IDE5OTcNCn0sDQp7DQoibWFrZSI6ICJOaXNzYW4iLCANCiJtb2RlbCI6ICJBbHRpbWEiLCANCiJ5ZWFyIjogMjAwNQ0KfQ0KXQ=="
}]

数据服务.ts

import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'

export interface Records {
    uid: number; 
    description_text: String;
    version_number: String; 
    mime_type: String; 
    file_item: Blob; 
}

@Injectable()
export class DataService {

    private baseURL = 'http://localhost:8080';

    constructor(private httpClient: HttpClient) { }

    getitems() {
        return this.httpClient.get(this.baseURL + '/getRecord');
    }
}

app.component.ts

export class AppComponent {
  title = 'angular-ui';
  items: Records[];
  ImageSource: any;

  constructor(private _ds: DataService, private sanitizer: DomSanitizer) { }

  ngOnInit() {
    this._ds.getitems().subscribe((data: Records[]) => {
      console.log(data);
      this.items = data;
    });
  }

  /* CRUD Methods [PrimeNG API] */
  onRowDownload(item: Records) {
    console.log(item.file_item);
    let objectURL = 'data:application/json;base64,' + item.file_item;
    this.ImageSource = this.sanitizer.bypassSecurityTrustUrl(objectURL);
    window.open(this.ImageSource);
  }
}

HTML

<p-table [value]="items" dataKey="uid">
  <ng-template pTemplate="header">
    <tr>
      <th>UID</th>
      <th>Description</th>
      <th>Version</th>
      <th>Mime Type</th>
      <th style="width:8em"></th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-rowData let-ri="rowIndex">
    <tr>
      <td>{{rowData.uid}}</td>
      <td>{{rowData.description_text}}</td>
      <td>{{rowData.version_number}}</td>
      <td>{{rowData.mime_type}}</td>
      <td style="text-align:center">
        <button pButton type="button" icon="pi pi-download" class="ui-button-info"
          (click)="onRowDownload(rowData)"></button>
      </td>
    </tr>
  </ng-template>
</p-table>

标签: angularspring-boot

解决方案


推荐阅读