【发布时间】:2017-07-02 02:07:40
【问题描述】:
我在尝试从前端上传照片时遇到问题。
我有一个输入文件,我可以从我的计算机中选择一个文件。
我想要的是将照片发送到我的后端并将其存储为 Blob。
首先我尝试获取文件并保存为 Blob:
foto: Blob;
setFoto(event){
this.foto = event.target.files[0];
}
但我不知道这是否正确。
其次,我使用 HTTP post 将“this.foto”发送到服务器,并在我的数据库中保存为 blob。我认为我的问题是我没有发送有关照片的正确信息。
在简历中,我想要将我从计算机中选择的图像发送到服务器,但在获取照片的正确信息时遇到问题。
解决方案成立
首先,这是我的输入:
<input type="file" (change)="setFoto($event)">
其次,这里是你选择照片时调用的方法。
setFoto(event) {
const foto = new Blob([event.target.files[0]]);
var reader = new FileReader();
reader.readAsDataURL(foto);
reader.onloadend = () => {
this.foto = reader.result;
}
}
this.foto 是一个字符串。 然后,当我单击更新按钮时,我将新照片作为 url 发送并作为文本保存在我的数据库(Mysql)中。
updateApuesta() {
this.userService.updateBet(this.url, {
id: this.userService.getIdbet(),
coste: this.coste,
beneficio: this.beneficio,
foto: this.foto
}).subscribe(this.success.bind(this), this.error);
}
当我尝试从我的服务器获取照片时,我使用它。我调用我的 http get 服务并获取照片。
首先,新图像是一个
image: SafeResourceUrl;
然后我分配从服务器获取的数据。
this.image = this.sanitizer.bypassSecurityTrustResourceUrl(data.foto);
你必须导入:
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
并将其传递给您的构造函数:
constructor(private sanitizer:DomSanitizer ) { }
最后,您在 this.image 中获得了属于 SafeResourceUrl 类型的图像。要加载它,你必须这样做:
<img [src]="bet.foto"/>
在你的情况下 bet.foto 将是你必须传递给模板的 this.image。
【问题讨论】:
-
你能发布你的http post请求吗
标签: node.js angular typescript