【发布时间】:2019-03-04 22:02:17
【问题描述】:
我在 Angular 6 中有一个简单的反应形式,它还有一个文件输入来上传图像。
场景是提交表单,保存表单的图像和文本字段,然后使用新图像更新照片库。对于照片库,我使用ng carousel。
这是前端的代码
<form [formGroup]="myForm" (ngSubmit)="submitForm($event.target)" >
<input type="file" (change)='imageChange($event)' formControlName="imageInput" name = 'imageInput'>
<input type="text" formControlName="imageName" name='imageName'>
<button type="submit" >Submit</button>
</form>
像这样保存
submitForm(form){
let formData = new FormData(form);
this.http.post('http://localhost:3000/cms/upload',formData,{reportProgress:true,observe:'events'}).subscribe(
event=>{
if(event.type === HttpEventType.Response){
eb = event.body;
this.addpic(eb.data);
}
});
}
eb.data包含来自服务器的数据,成功保存表单数据后,新图像的id和文件名。
在addpic 中,我尝试在轮播中添加新图像。将所有新数据添加到一个数组中,以便我以后可以使用该数组,ngFor 它并动态创建 ng Carousel
addpic(data){
this.images.push({
'id': data.id,
'name': data.name
});
}
像这样使用它
<ngb-carousel #carousel *ngIf="images" >
<ng-template ngbSlide *ngFor="let im of images; let i = index" id="{{im.id}}">
<img src='../assets/images{{im.newName}}' >
</ng-template>
</ngb-carousel>
所以这工作正常,但图像永远不会被渲染。我没有收到任何错误,我看到所有数据都保存在我的数据库中,图像按应有的方式传输到文件夹中,但轮播中没有新图像,控制台中只有 404 错误。 images 数组已更新,但轮播中没有图像。 URL 没问题,所有其他具有相同 URL 的图像都在轮播中呈现。就像应用程序没有时间看到整个更新,所以它无法显示图像。
我试图从表单中获取图像文件对象,将其以角度保存在 selectedFile: File; 中并在轮播中使用它,但它没有 path 或类似的东西。在表单中设置时抓取它
imageChange(e){
this.selectedFile = e.target.files[0];
}
并在addpic中使用它
addpic(data){
this.images.push({
'id': data.id,
'name': this.selectedFile.path
});
}
我也试过在表单提交前使用formData,得到图片,但结果是一样的,一个没有路径的对象。
我还尝试使用 HTML5 FileReader“读取”文件,但这是一个图像,在轮播中,我需要提供src 的 URL,而不仅仅是图像文件。
我还在节点中使用了强大的功能来解析表单并获取图像的路径,将其连同 id 和文件名一起返回到前端,并将其用作src。但我猜出于安全原因,浏览器不会使用它,因为它是临时文件中的 URL。
我也尝试通过查询从服务器获取所有图像,但新图像仍然不可用,给出 404 错误,即使图像在文件夹中并且数据库已更新。
喜欢这个
addpic(data){
this.getImages(this.currentId); //get all images again
this.images.push({
'id': this.images.id,
'name': this.images.path
});
}
我必须刷新页面才能显示图像。我不知道如何解决这个问题。有任何想法吗?即使保存了图像并且我必须刷新,我也无法立即获取图像,这是否是一个安全问题?如果可能的话,我想避免执行额外的get,以保持客户端-服务器通信最少。
我使用 angular6 和节点 8.11。在 Windows 10 中,全部在我的笔记本电脑本地。
谢谢
【问题讨论】:
标签: node.js angular object file-upload blob