angular 上传图片并显示_ionic2+Angular 使用ng2-file-upload 插件上传图片并实现本地预览...

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= newFileReader();

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

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值