typescript 在没有 jQuery 的情况下将图像上传到服务器之前,如何从输入标签中获取 Angular 2(或更高版本)中图像的高度和宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50566385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the height and width of an image in Angular 2(or above) from input tag before uploading it to the server without jQuery?
提问by Vijay
I checked various sources but most of the solutions are in jQuery. I want the solution in Typescript if possible.
我检查了各种来源,但大多数解决方案都在 jQuery 中。如果可能,我想要 Typescript 中的解决方案。
HTML -
HTML -
<input #coverFilesInput class="file-input" type="file"(change)="onChange($event)"....>
<input #coverFilesInput class="file-input" type="file"(change)="onChange($event)"....>
Typescript -
打字稿 -
onChange($event) { let img = event.target.files[0]; // and then I need code to validate image size }
Is there a solution or am I doing it completely wrong?
有没有解决办法,还是我做的完全错了?
回答by Niladri
You can use the combination of @ViewChild and ElementRef
to access the file upload control and clear it's value after every upload otherwise the (change)
event would not fire.
您可以使用 的组合@ViewChild and ElementRef
来访问文件上传控件并在每次上传后清除它的值,否则(change)
事件不会触发。
And then you can use FileReader()
to read the file into an Image
object and get the width and height from it.
然后您可以使用FileReader()
将文件读入Image
对象并从中获取宽度和高度。
Here is the code below -
这是下面的代码 -
HTML template
HTML模板
<input type="file" #coverFilesInput (change)="onChange($event)" class="file-input" />
Upload Percent: {{percentDone}}% <br />
<ng-container *ngIf="uploadSuccess">
Upload Successful of file with size : {{size}} bytes <br>
The image height is : {{height}} <br>
The image width is : {{width}} <br>
</ng-container>
The onChange method
onChange 方法
onChange(evt:any){
this.percentDone = 100;
this.uploadSuccess = true;
let image:any = evt.target.files[0];
this.size = image.size;
let fr = new FileReader();
fr.onload = () => { // when file has loaded
var img = new Image();
img.onload = () => {
this.width = img.width;
this.height = img.height;
};
img.src = fr.result; // The data URL
};
fr.readAsDataURL(image);
this.imgType.nativeElement.value = ""; // clear the value after upload
}
complete code app.component.ts
完整代码 app.component.ts
import { Component, VERSION ,ViewChild,ElementRef} from '@angular/core';
import {HttpClientModule, HttpClient, HttpRequest, HttpResponse, HttpEventType} from '@angular/common/http';
@Component({
selector: 'my-app',
template: `
Version = {{version.full}} <br/>
<input type="file" #coverFilesInput (change)="onChange($event)" class="file-input" />
Upload Percent: {{percentDone}}% <br />
<ng-container *ngIf="uploadSuccess">
Upload Successful of file with size : {{size}} bytes <br>
The image height is : {{height}} <br>
The image width is : {{width}} <br>
</ng-container>
`,
})
export class AppComponent {
percentDone: number;
uploadSuccess: boolean;
size:any;
width:number;
height:number;
@ViewChild('coverFilesInput') imgType:ElementRef;
constructor(
) { }
version = VERSION
onChange(evt:any){
this.percentDone = 100;
this.uploadSuccess = true;
let image:any = evt.target.files[0];
this.size = image.size;
let fr = new FileReader();
fr.onload = () => { // when file has loaded
var img = new Image();
img.onload = () => {
this.width = img.width;
this.height = img.height;
};
img.src = fr.result; // This is the data URL
};
fr.readAsDataURL(image);
this.imgType.nativeElement.value = "";
}
}
Here is a working demo : https://stackblitz.com/edit/angular-file-upload-hnik7q
这是一个工作演示:https: //stackblitz.com/edit/angular-file-upload-hnik7q
Edit :you can also use [(ngModel)]="selectedFile"
to access the input file control and clear it's value after the validation and upload is done without using @ViewChild
and ElementRef
like below -
编辑:您还可以使用[(ngModel)]="selectedFile"
访问输入文件控件并在验证和上传完成后清除它的值而不使用@ViewChild
,ElementRef
如下所示 -
<input type="file" #coverFilesInput (change)="onChange($event)" class="file-input" [(ngModel)]="selectedFile"/>
and in component class -
在组件类中 -
export class AppComponent {
percentDone: number;
uploadSuccess: boolean;
size:any;
width:number;
height:number;
selectedFile:any; // declare the property
constructor(
) { }
version = VERSION
onChange(evt:any){
this.percentDone = 100;
this.uploadSuccess = true;
let image:any = evt.target.files[0];
this.size = image.size;
let fr = new FileReader();
fr.onload = () => { // when file has loaded
var img = new Image();
img.onload = () => {
this.width = img.width;
this.height = img.height;
};
img.src = fr.result; // This is the data URL
};
fr.readAsDataURL(image);
this.selectedFile = ""; // clear the file here
}
}
回答by Ryan J
Try using the ElementRef.
尝试使用ElementRef。
First you need to mark your dom element #myImage
首先你需要标记你的dom元素 #myImage
Then in your component class you can target the dom element with ViewChild
然后在您的组件类中,您可以使用ViewChild定位 dom 元素
ViewChild('myImage')
myImage: ElementRef;
ViewChild('myImage')
myImage: ElementRef;
Once the view is loaded you can extract the image details
加载视图后,您可以提取图像详细信息
ngAfterViewInit() {
console.log(this.myImage.nativeElement.offsetWidth);
console.log(this.myImage.nativeElement.offsetHeight);
}
ngAfterViewInit() {
console.log(this.myImage.nativeElement.offsetWidth);
console.log(this.myImage.nativeElement.offsetHeight);
}
Since you are just extracting information about the dom element, the security risk is low. I would advise you not to modify dom elements using this method.
由于您只是提取有关 dom 元素的信息,因此安全风险较低。我建议您不要使用这种方法修改 dom 元素。
回答by Cristian ventura
Try this way, it's work for me!!
试试这个方法,它对我有用!!
// in your .html file
<input type="file" class="form-control"
accept="image/*"
(change)="onChange($event)">
// in your .ts file
onChange(fileInput: any) {
const URL = window.URL || window.webkitURL;
const Img = new Image();
const filesToUpload = (fileInput.target.files);
Img.src = URL.createObjectURL(filesToUpload[0]);
Img.onload = (e: any) => {
const height = e.path[0].height;
const width = e.path[0].width;
console.log(height,width);
}
}