第一步:npm install ng2-file-upload --save 安裝 ng2-file-uploadhtml
第二步:在須要使用該插件的頁面的對應module文件的imports中引入CommonModule 和 FileUploadModulenpm
第三步:在對應的組件文件中引入並聲明;數組
2017-08-07補充:服務器
如下是new FileUploader()須要傳入的參數列表,?號表示可選:ionic
第四步:在組件.ts對應的html文件中添加input標籤;以下:this
2017-08-07附加刪除圖片的邏輯處理:lua
你們能夠參考一下選擇的圖片在uploader:FileUploader中的存儲規則url
第七步:完成圖例:spa
後記:2017-07-21 10:44插件
若是出現下圖的錯誤,肯能是由於沒有導入第二步中的相關文件,也有多是由於在第四步的input元素設置中缺乏了ng2FileSelect
2017-08-07 17:00補充邏輯處理的代碼:
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { FileUploader } from 'ng2-file-upload'; @IonicPage({ name: 'orderEvaluate', segment: 'orderEvaluate' }) @Component({ selector: 'page-order-evaluate', templateUrl: 'order-evaluate.html', }) export class OrderEvaluatePage { public uploader: FileUploader = new FileUploader({ url: '圖片上傳地址' }); selectedImgUrl: any[] = [];//存儲已經選擇的圖片 selectedImgLength = 0; constructor( public navCtrl: NavController, public navParams: NavParams) { } removeUpload(img) { //刪除圖片 this.uploader.queue[img.uploadID].remove(); this.selectedImgUrl.splice(img.uploadID, 1); this.selectedImgUrl.forEach((up, i) => { up.uploadID = i//重構與上傳數據一致的結構 }); this.selectedImgLength = this.uploader.queue.length; console.log(this.uploader); } selectedFileOnChanged(index: number) { //選擇圖片 let $this = this;//區別於new FileReader()中的this let selectedArr = this.selectedImgUrl;//存儲選擇的圖片並進行標記存儲 this.uploader.queue.forEach((q, i) => { //this.selectedImgLength記錄已選擇的總的圖片數量。並根據此來判斷圖片如何進行存儲; if (this.selectedImgLength == 0 || i > this.selectedImgLength - 1) { let reader = new FileReader(); reader.readAsDataURL(q.some);//生成base64圖片地址,實現本地預覽。只是same屬性被protected修飾,須要修改。 reader.onload = function () { let imgs = { url: this.result,//當前選擇的圖片生成的base64圖片地址 uploadID: i,//該圖片在隊列中的位置標記 pIndex: index//當前上傳的圖片所屬,由於若是是訂單評價的話,會存在多個商品,index就是標記上傳的是哪一個商品的評價圖。 }; if (selectedArr.length > 0) { let isSame = false;//標識是否選擇過同一張圖片 selectedArr.forEach((img, j) => { if (img.url == this.result) { isSame = true; } }); if (!isSame) { //避免選擇相同的圖片 selectedArr.push(imgs); } else { $this.uploader.queue[i].remove();//若是已經選擇,就須要在隊列中移除該圖片 $this.selectedImgLength = $this.uploader.queue.length;//並更新已選圖片數量 } } else { selectedArr.push(imgs) } } } }); this.selectedImgLength = this.uploader.queue.length; } uploadImg() { let $this = this; this.selectedImgUrl.forEach((img, i) => { //在上傳的this.uploader隊列中標記圖片所屬;根據項目需求 //若是同時對多個商品進行評價並上傳圖片,全部商品選擇的圖片是存儲在同一個數組中, //因此上傳以前須要標識屬於哪一個商品,上傳成功以後返回的數據一樣會帶有標識 this.uploader.queue[i]['pIndex'] = img.pIndex; }); this.uploader.uploadAll() // 開始上傳 this.uploader.onSuccessItem = (item, res, status, headers) => { // 單張圖片上傳文件成功 //上傳多張圖片的話會執行屢次 if (status == 200) { // 上傳文件成功後獲取服務器返回的數據 //根據項目需求處理返回來的數據; } else { // 上傳文件後獲取服務器返回的數據錯誤 } }; this.uploader.onCompleteAll = function () { //uploader: FileUploader服務是單張上傳圖片, //onCompleteAll能夠檢測到圖片所有上傳完成 //所有圖片上傳結束 //通常上傳圖片和上傳其餘評價的信息接口都是分開的,能夠在此方法中構建須要上傳的數據模型並調取相關接口 //over } } }