你想在Angular應用程序中進行圖片上傳,是否想在圖片上傳之前在前端限制上傳圖片的尺寸?ng2-img-max模塊正是你所要的! ng2-img-max模塊會使用web sorkers 進行圖片大小的計算,并駐留在主線程中。
我們來看看他的用途:
安裝
首先,使用npm 或 Yarn安裝模塊:
$ npm install ng2-img-max blueimp-canvas-to-blob --save# or Yarn :$ yarn add ng2-img-max blueimp-canvas-to-blob
blueimp-canvas-to-blob是一個polyfill,以便canvas.toBlob()可以在Safari和舊版本的Internet Explorer等瀏覽器上使用。
將polyfill腳本包含在項目中。 如果您使用Angular CLI,您可以將腳本添加到.angular-cli.json文件中:
//: .angular-cli.json..."scripts": [ "../node_modules/blueimp-canvas-to-blob/js/canvas-to-blob.min.js"],//...
將腳本添加到Angular CLI配置后,您將需要重新啟動本地服務。
現在我們將模塊導入應用模塊或功能模塊:
//: app.module.ts//...import { Ng2ImgMaxModule } from 'ng2-img-max';@NgModule({ declarations: [ AppComponent ], imports: [ //... ng2ImgMaxModule ], providers: [], bootstrap: [ AppComponent ]})export class AppModule {}最后,ng2-img-max服務可以導入并注入到這樣的組件中:
import { Component } from '@angular/core';import { Ng2ImgMaxService } from 'ng2-img-max';@Component({ ... })export class AppComponent { constructor(private ng2ImgMax: Ng2ImgMaxService ) {}}使用
我們添加一個File文件輸入框到組件的模板中,像這樣:
<input type='file' (change)="onImageChange($event)" accept="image/*" />
在組件類中添加方法onImageChange, 它將會限制圖片的寬高為:400px,300px:
updateImage: Blob;constructor(private ng2ImgMax: Ng2ImgMaxService) {}onImageChange(event){ let image = event.target.files[0]; this.ng2ImgMax.resizeImage(image,400,300).subscribe(result=> { this.uploadImage = result; }, error=> { console.log('error:',error); })}如果您有多個圖像需要一次性調整大小,請改用resize方法,并將圖片文件數組作為第一個參數傳入。
結果是Blob類型,但是如果需要,可以使用File構造函數將其轉換為正確的文件:
//: app.component.tsuploadedImage: File;constructor(private ng2ImgMax: Ng2ImgMaxService) {}onImageChange(event){ let image = event.target.files[0]; this.ng2ImgMax.resizeImage(image,400,300).subscribe(result=> { this.uploadedImage = new File([result],result.name); }, error=> { console.log('error',error); })}您現在可以將文件上傳到您的后端。 不要忘記在后端做好驗證,因為這里的內容會阻止一些用戶將超大或非圖像文件直接上傳到后端。
新聞熱點
疑難解答
圖片精選