在Angular中将src动态分配给图像

时间:2019-09-30 08:24:39

标签: javascript node.js angular

我尝试在Angular中上传文件。我添加了一个按钮,该按钮将该帖子称为一种将图像写入数据库并将其保存到“资产”文件夹的方法。此图像必须显示在中。此文件已成功发布并存储在资产上,但没有显示,我得到了error

但是在我重新加载Angular CLI服务器之后,它已经可以工作了。

我的输入

<div class="form-group">
        <label for="inputPhotoGame">Select a game photo</label>
        <input type="file" class="form-control-file" id="inputPhotoGame" (change)="fileProgress($event)">
      </div>

我的img

<img alt="photo" [src]=game.img_game>'''

Component class
'''import { Component, OnInit } from '@angular/core';

import {Genre} from '../../models/Genre';
import {MatIconRegistry} from '@angular/material';
import {CustomIconService} from '../../services/CustomIconService';
import {Game} from '../../models/Game';
import {FormComponent} from '../form/form.component';
import {GameService} from '../../services/GameService';

@Component({
  selector: 'app-add-game',
  templateUrl: './add-game.component.html',
  styleUrls: ['./add-game.component.scss']
})
export class AddGameComponent implements OnInit {

  genresList: Genre [];
  searchStringForFiltrSearchArcade: string = '';
  selectedPlatformIcon: string = '';
  fileToUpload: File = null;
  game: Game = new Game();
  previewUrl:any = null;

  constructor(private customIconService: CustomIconService, private gameService: GameService) {
    this.customIconService.init();
    this.genresList = [{name: 'Arcada'}, {name: 'Sport Simulator'}, {name: 'MOBA'}, {name: 'MMO RPG'}, {name: 'RPG'}, {name: 'Shuter'}];
  }

  ngOnInit() {
  }

  changePlatform() {
    switch (this.game.platform_game) {
      case 'Xbox': {
        this.selectedPlatformIcon = 'icon-xbox';
        break;
      }
      case 'PlayStation': {
        this.selectedPlatformIcon = 'icon-ps';
        break;
      }
      case 'PC': {
        this.selectedPlatformIcon = 'icon-pc';
        break;
      }
      default: alert("Error");
    }
  }

  handleFileInput(fileInput: any){
    // this.fileToUpload = files.item(0);
    // console.log(this.fileToUpload);
    // this.gameService.postFile(this.fileToUpload,"16");
    // alert("file upload")
  }

  fileProgress(fileInput: any) {
    this.fileToUpload = <File>fileInput.target.files[0];
    this.preview();
  }

  preview() {
    let mimeType = this.fileToUpload.type;
    if (mimeType.match(/image\/*/) == null) {
      return;
    }
    let reader = new FileReader();
    reader.readAsDataURL(this.fileToUpload);
    reader.onload = (_event) => {
      this.previewUrl = reader.result;
    };
    this.gameService.postFile(this.fileToUpload,"16");
  }
}

服务等级

import {Injectable} from "@angular/core";
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
import {Game} from "../models/Game";

@Injectable()
export class GameService {

  private readonly usersUrl: string;

  constructor(private httpClient: HttpClient) {
    this.usersUrl = 'http://localhost:8080/api/v1/all';
  }

  public find(): Observable<Game[]> {

    return this.httpClient.get<Game[]>(this.usersUrl);
  }

  postFile(fileToUpload: File, idGame: string) {
    const endpoint = 'http://localhost:8080/api/v1/uploadFile/'+idGame;
    const formData: FormData = new FormData();
    formData.append('file', fileToUpload, fileToUpload.name);
    this.httpClient
      .post(endpoint, formData, { headers: {"cache-control": "no-cache"} }).subscribe((val) => {
        console.log(val);
      });
    return false;
  }
}

和html页面 error

After reload Angular CLI server

1 个答案:

答案 0 :(得分:1)

执行“ ng服务”时,您的应用已加载到内存中。在资产中添加文件不会使它们在内存中。 您应该从api中获取文件(类似http://localhost:8080/api/v1/file/FileID