如何在元素中处理图像输入到 Angular 应用程序<img>?



我正在尝试创建一个能够拍摄照片的Angular PWA,并在拍摄后将其显示在img元素中。

我成功的第一步:我现在有了一个FAB按钮,可以打开相机取景器(使用html输入标签(,其中有一小段代码:

const element: HTMLElement = document.getElementById('imageCapturer') as HTMLElement;
element.click();

这模拟点击以下HTML元素:

<input type="file" accept="image/*" capture="environment" id="imageCapturer"">

然而,拍完照片后,我想使用图像在img元素中渲染它(并通过API调用将图像发送到数据库(

我尝试了多种解决方案,包括尝试将file.name作为src添加到img元素,以及尝试创建一个新的img HTML元素,该元素具有使用该文件的属性。但是我仍然无法处理要在img标记中使用的图像。有人能向我解释一下处理文件的正确方法是什么吗?

干杯!

我通过以下方式解决了这个问题:

首先,我将HTML更改为:

<input type="file" accept="image/*" id="imageCapturer" style="display: none;" (change)="useImage($event)">
<img *ngIf="URL" [src]="URL" id="imageViewer">

然后函数useImage看起来像这样:

useImage(event) {
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // Read file as data url
reader.onloadend = (e) => { // function call once readAsDataUrl is completed
this.URL = e.target['result']; // Set image in element
this._changeDetection.markForCheck(); // Is called because ChangeDetection is set to onPush
};
}

}

现在,每当捕捉或选择新图像时,它都会在视图中更新

您可以使用输入文件的事件更改。这个例子:

$('#imageCapturer').on('change', function () {
var input = $(this)[0];
if (input.files && input.files[0]) {
var fileName= input.files[0].name;
var reader = new FileReader();
reader.onload = function (e) {
var buffer = e.target.result;
var fileSize = input.files[0].size / 1024 / 1024; // in MB
// SET IMG DISPLAY
$('#image-display').attr('src', buffer).css({
'max-height': '170px',
'max-width': '170px',
};
reader.readAsDataURL(input.files[0]);
}
});

注意:当sumbit形式发送文件byte[]时,您在标记形式中添加了更多属性[Enttype="multipart/form-data"]。

<form id="process_form" method="POST" enctype="multipart/form-data" autocomplete="off" role="form" data-parsley-focus="none">