上传一个图片,并预览

2021-02-04  本文已影响0人  价值投机168

1.h5代码,做一个图片显示的:
<div style="width: 150px;height: 125px;display: flex;align-items: center;justify-content: center;">
<img [attr.src]= "testedByImage" *ngIf="testedByImage"/>
</div>
外面的div是占空间的。同时让图片永远居中。
2.让图片缩放不失真,添加css:
img{
width:auto;
height:auto;
max-width:100%;
max-height:100%;
}
3.在h5中添加按钮和上传文件的载体:
<div
style="background-color: #E9EDF0;width:80px;border: 1px solid lightgray;border-radius: 2px; margin: 2px;text-align: center;
cursor: pointer;" (click)="fileInput.value=null;fileInput.click()">
{{'CR.ILOGO' | translate }}</div>

<input type="file" #fileInput (change)="uploadFile()" style="display:none"
[accept]="'image/*'">
4.在cs文件中处理:
async uploadFile() {
if (this._fileInput.nativeElement.files && this._fileInput.nativeElement.files.length > 0) {
const file = this._fileInput.nativeElement.files[0];

        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = async (r) => {
            if (this.uploadLogoType === 1) {
                this.forImage = r.target.result as string;
            } else if (this.uploadLogoType === 2) {
                this.testedByImage = r.target.result as string;
            }
        };
    }
}

这样,图片就可以预览显示了。并且按比例缩放并居中。

上一篇 下一篇

猜你喜欢

热点阅读