我正在使用Angular版本8.0。 我想通过以下代码将图像存储在api中:
home.component.ts用于上传和显示图像
preview2(files) {
if (files.length === 0)
return;
var mimeType = files[0].type;
if (mimeType.match(/image\/*/) == null) {
this.message = "Only images are supported.";
return;
}
var reader = new FileReader();
this.imagePath = files;
reader.readAsDataURL(files[0]);
reader.onload = (_event) => {
this.imgURL2 = reader.result;
console.log(this.imgURL2);
console.log(reader);
this.med_limit2 = true;
}
}
home.component.html用于上传图片
<input #file2 type="file" class="file_upload" accept='image/*' (change)="preview2(file2.files)" />
<button class="btn btn-primary" style="width: 50%;background: #0b474a;
border: none;">Browse</button>
``
home.component.html for showing Image
<img [src]="imgURL2" *ngIf="imgURL2" class="presc_img" data-toggle="modal" data-target="#exampleModal2"
style="max-width: 123px; min-width: 99px; margin: 0 14px;box-shadow: 0px 1px 3px 0px grey;
border-radius: 2px;">
upload_image() {
this.presc_service.uploadPrescriptionImage(this.imgURL2).subscribe(res => {
console.log(res);
this.image_upload2 = '/' + res['cart_data'][0]
this.uploadStatus = res['status']
});
}
home.component.ts
onSelectFile(event) {
console.log(event);
if (event.target.files && event.target.files[0]) {
this.imageToUpload = event.target.files[0];
console.log(this.imageToUpload);
const reader = new FileReader();
reader.onload = e => this.selectedImage = reader.result.toString();
this.fileName = event.target.files[0].name;
reader.readAsDataURL(this.imageToUpload);
}
}
我有使用api存储图像的代码,但没有预览图像
答案 0 :(得分:0)
我的问题解决了。 感谢您的帮助。
home.component.ts
onSelectFile(event, files) {
if (files.length === 0)
return;
var mimeType = files[0].type;
if (mimeType.match(/image\/*/) == null) {
this.message = "Only images are supported.";
return;
}
console.log(event);
if (event.target.files && event.target.files[0]) {
this.imageToUpload = event.target.files[0];
console.log(this.imageToUpload);
const reader = new FileReader();
reader.onload = e => this.selectedImage = reader.result.toString();
this.fileName = event.target.files[0].name;
reader.readAsDataURL(this.imageToUpload);
var reader1 = new FileReader();
this.imagePath = files;
reader1.readAsDataURL(files[0]);
reader1.onload = (_event) => {
this.imgURL = reader1.result.toString();
console.log(this.imgURL);
console.log(reader1);
this.med_limit1 = true;
}
}
}