我试图创建角度2/4服务,有可能上传文件。我在任何资源上都找不到解决方案,所以我可能想问你们。所以这个想法是在组件的某个地方,有一个类型为file的输入字段。它具有指令(change)=“uploadFile($event)”。
uploadFile(event) {
this.images.push(this.uploadImgService.uploadImage(event));
}
UploadImgService看起来是这样的:
private img: string;
uploadImage(e) {
const file = e.target.files[0];
const pattern = /image-*/;
if (!file.type.match(pattern)) {
alert('You are trying to upload not Image. Please choose image.');
return;
}
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
this.img = reader.result;
};
return this.img;
}
所以,我知道操作是异步的,但我不知道如何包装它,直到img加载。我认为这是技能缺乏的结果:(
当我把这段代码发布到组件中时,它肯定会工作,但我的想法是提供服务。
而且,我只是一个角度的初学者。因此,如果有更好的方法来实现这个想法,我很高兴收到你的来信。谢谢