【发布时间】:2018-01-08 18:18:41
【问题描述】:
我正在尝试通过这个小例子来了解 angular bei 的一些特性。
从<input type="file"> 用户选择一个图像文件。然后 HttpClient 向后端(nodejs)发送 post 请求,以将选定的图像文件保存到我的 Angular 5 Web 应用程序中的文件夹 src/assets/images 中。到现在为止一切正常。
我的实验
我想在该输入字段下方的div 中显示导入 图像。
问题
我明白了
尽管IMG2.jpg 已通过后端成功添加到src/assets/images。
我的问题
- 如何强制
ng serve感知应用于 angular-app 文件结构的后端更改? - 使用此类标记
<img [src]="img.path"> <!-- my variable in component.ts -->是一种好习惯吗?
我正在使用 angular5,angular-cli: 1.5.4,typescript ~2.4.2,OSX 10.13.2,node 8.9.1,npm 5.5.1。
提前谢谢你。
如果您有兴趣查看我的代码
component.ts:
import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'screenshot',
templateUrl: './screenshot.component.html',
styleUrls: ['./screenshot.component.css']
})
export class ScreenshotComponent implements OnInit {
@Input('images') images: any[] = [];
fileInput: HTMLInputElement;
ngOnInit() {
}
// the magic was brought to you from
https://gist.github.com/aitoribanez/8b2d38601f6916139f5754aae5bcc15f
filesToUpload: any[] = [];
constructor(private http: HttpClient) { }
/**
* this will be called, wenn the button "Einfuegen" is clicked!
*/
upload(form: HTMLFormElement) {
const formData: any = new FormData();
const files: Array<any> = this.filesToUpload;
formData.append("uploads", files[0], files[0]['name']);
console.log(formData);
this.http.post('http://localhost:3001/upload', formData)
.subscribe(files => {
console.log('files', files)
this.images.push({
name: files[0].filename,
path: "assets/images/" + files[0].filename
});
console.log("images list", this.images);
})
// To reset the input field
this.fileInput.value = "";
}
fileChangeEvent(event: any) {
this.filesToUpload = event.srcElement.files;
console.log(this.filesToUpload);
this.fileInput = event.srcElement;
}
}
component.html
<div>
<input type="file" accept=".png, .jpg, .jpeg" (change)="fileChangeEvent($event)">
<button type="submit">Eingfuegen!</button>
<div [(ngModel)]="images" *ngIf="images.length > 0" name="displayImages" ngDefaultControl>
<div class="myphoto" *ngFor="let img of images">
<img [src]="img.path" alt="{{img.name}}">
</div>
</div>
</div>
【问题讨论】:
-
当您将“文件”记录到控制台时,文件会显示出来吗?
-
是的,确实如此,这是日志:
files [{…}] 0 : destination : "./../src/assets/images" encoding : "7bit" fieldname : "uploads" filename : "test3.png" mimetype : "image/png" originalname : "test3.png" path : "../src/assets/images/test3.png" size : 10086 __proto__ : Object length : 1 __proto__ : Array(0)
标签: angular image typescript angular-cli property-binding