ionic3 上传图片 视频 (包括拍照上传和从手机相册选择上传)

  • Post author:
  • Post category:其他


初学ionic3 ,下面是在实际应用中上传图片和视频,样式和效果虽然有待改善,但是功能上已经实现图片上传和视频上传,所以发个博客备用看,肯定有很多不足,望指正.


ionic3 使用上传图片、视频,需要下载插件来支持功能的实现,然后才可以在ts中引用、定义


相机插件:


ionic plugin add cordova-plugin-camera


上传文件插件:


ionic plugin add cordova-plugin-file-transfer


调用相册插件:


ionic cordova plugin add cordova-plugin-telerik-imagepicker

ts中:

import { Component } from ‘@angular/core’;

import { IonicPage, NavController, NavParams,ActionSheetController,ToastController, Picker } from ‘ionic-angular’;

import { ImagePicker } from “@ionic-native/image-picker”;

import { Camera, CameraOptions } from ‘@ionic-native/camera’;

import { FileTransfer, FileTransferObject, FileUploadOptions } from “@ionic-native/file-transfer”;

import { UtilService, AppGlobal } from ‘../../providers/util.service’;

import { DomSanitizer } from ‘@angular/platform-browser’;

@IonicPage()

@Component({


selector: ‘asd’,

templateUrl: ‘asd.html’,

})

export class Asd {

constructor(public navCtrl: NavController, public navParams: NavParams,

public toastCtrl: ToastController,

public utilService: UtilService,

public toast: ToastController,

public actionSheetController: ActionSheetController,

public camera: Camera,

public transfer: FileTransfer,

private imagePicker: ImagePicker,

public sanitizer: DomSanitizer) {

}


//定义粗放图片路径的数组


productInfo = [];


// 上传图片


async presentActionSheet() {


const actionSheet = await this.actionSheetController.create({


buttons: [{


text: ‘拍照’,

handler: () => {


console.log(‘拍照’);

this.takePhoto();

}

}, {


text: ‘相册’,

handler: () => {


console.log(‘相册’);

this.chooseFromAlbumPic();

}

}, {


text: ‘取消’,

role: ‘cancel’,

handler: () => {


console.log(‘Cancel clicked’);

}

}]

});

await actionSheet.present();

}


// 拍照上传


takePhoto() {


const options: CameraOptions = {


quality: 100,

allowEdit: false,

targetWidth: 1000,

targetHeight: 1000,

saveToPhotoAlbum: false,

destinationType: 1,

encodingType: 0,

mediaType: 0,

};

this.camera.getPicture(options).then(image => {


let toast = this.toastCtrl.create({


message: ‘上传中…’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “success”

});

toast.present();

let options: FileUploadOptions = {


fileKey: “file”,

fileName: image,

mimeType: “image/jpeg”

};

var ftObj: FileTransferObject = this.transfer.create();


//AppGlobal.domain1 + AppGlobal.API1.addFile 此处为拼接的后台上传路径


ftObj.upload(image, encodeURI(AppGlobal.domain1 + AppGlobal.API1.addFile), options).then(

(data) => {


var picjson = $.parseJSON(data.response);

this.productInfo.push(picjson.msg);

let toast = this.toastCtrl.create({


message: ‘上传成功’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “success”

});

toast.present();

this.utilService.hideLoading();

},

(err) => {


let toast = this.toastCtrl.create({


message: ‘上传失败’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “error”

});

toast.present();

});

}, error => {


console.log(AppGlobal.domain1 + AppGlobal.API1.addFile);

console.log(‘上传失败: ‘ + error);

let toast = this.toastCtrl.create({


message: ‘上传失败’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “error”

});

toast.present();

});

}


// 从图库选择图片


chooseFromAlbumPic() {


let options = {


maximumImagesCount: 5,    // 最多传几张

width: 800,

height: 800,

quality: 100,// 图片质量

outputType: 0,

};

this.imagePicker.getPictures(options).then((results) => {


var ftObj: FileTransferObject = this.transfer.create();

if (JSON.stringify(results) != null || JSON.stringify(results) != “”) {


let toast = this.toastCtrl.create({


message: ‘上传中…’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “success”

});

toast.present();

}

for (var i = 0; i < results.length; i++) {


let options: FileUploadOptions = {


fileKey: “file”,

fileName: results[i],

mimeType: “image/jpeg”

};

ftObj.upload(results[i], encodeURI(AppGlobal.domain1 + AppGlobal.API1.addFile), options).then(

(data) => {


var picjson = $.parseJSON(data.response);

this.productInfo.push(picjson.msg);

console.log(this.productInfo);

let toast = this.toastCtrl.create({


message: ‘上传成功’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “success”

});

toast.present();

if (i == (results.length – 1)) {


this.utilService.hideLoading();

}

},

(err) => {


let toast = this.toastCtrl.create({


message: ‘上传失败’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “error”

});

toast.present();

});

}

}, (err) => {


let toast = this.toastCtrl.create({


message: ‘上传失败’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “error”

});

toast.present();

});

}


// 删除图片


delete_img(e: number) {


var productInfo = this.productInfo;

productInfo.splice(e, 1);

this.productInfo = productInfo;

}


//回显图片


changeImg(img) {


return this.sanitizer.bypassSecurityTrustStyle(`url(${img})`);

}


// 上传视频


productInfo1 = [];

async presentAction() {


const actionSheet = await this.actionSheetController.create({


buttons: [

{


text: ‘视频’,

handler: () => {


console.log(‘视频’);

this.chooseAudio();

}

}, {


text: ‘取消’,

role: ‘cancel’,

handler: () => {


console.log(‘Cancel clicked’);

}

}]

});

await actionSheet.present();

}


// 从图库选择视频


chooseAudio() {


let options = {


sourceType: 0,//选择类型为视频

width: 800,

height: 800,

mediaType: 1,//0为图片,1为视频

allowEdit: true,

};

this.camera.getPicture(options).then((results) => {


var ftObj: FileTransferObject = this.transfer.create();

// this.utilService.toast(‘上传中’);

let toast = this.toastCtrl.create({


message: ‘上传中…’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “success”

});

toast.present();

let options: FileUploadOptions = {


fileKey: “file”,

fileName: results,

mimeType: “video/mp4”,

};

ftObj.upload(results, encodeURI(AppGlobal.domain1 + AppGlobal.API1.addFile), options).then(

(data) => {


var picjson = $.parseJSON(data.response);

this.productInfo1.push(AppGlobal.domain1 + picjson.msg);

console.log(this.productInfo);

document.getElementById(“videoSql”).style.display = “none”;

let toast = this.toastCtrl.create({


message: ‘上传成功’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “success”

});

toast.present();

this.utilService.hideLoading();

},

(err) => {


let toast = this.toastCtrl.create({


message: ‘上传失败’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “error”

});

toast.present();

});

}, (err) => {


let toast = this.toastCtrl.create({


message: ‘上传失败’,

duration: 1000,

position: ‘middle’,//位置

cssClass: “error”

});

toast.present();

});

}


// 删除视频


delete_video(e: number) {


var productInfo1 = this.productInfo1;

productInfo1.splice(e, 1);

this.productInfo1 = productInfo1;

}

html中:

<div class=”cu-bar bg-white margin-top”>

<div class=”action”> 图片: </div>

</div>

<div class=”cu-form-group”>

<div class=”grid col-4 grid-square flex-sub”>

<div class=”padding-xs bg-img” *ngFor=”let item of productInfo;let i = index;”

[style.background-image]=”changeImg(item)”>

<div (click)=’delete_img(i)’ class=”cu-tag bg-red”>

<span (click)=’delete_img(i)’ class=’cuIcon-close’></span>

</div>

</div>

<div *ngIf=”productInfo == null || productInfo.length < 5″ class=”padding-xs solids”

(click)=’presentActionSheet()’>

<span class=’cuIcon-cameraadd’></span>

</div>

</div>

</div>


<div class=”cu-bar bg-white margin-top”>

<div class=”action”> 视频: </div>

</div>

<div id=”videoSql”>

</div>

<div class=”cu-form-group” style=”margin-bottom: 10px;padding-bottom: 20px;”>

<div class=”padding-xs bg-img” *ngFor=”let item of productInfo1;let i = index;”>

<video style=”width: 100%;height: 180px;” src=”{

{item}}” controls=”{

{true}}”>

</video>

<div (click)=’delete_video(i)’ class=”cu-tag bg-red”>

<span (click)=’delete_vIdeo(i)’ class=’cuIcon-close’></span>

</div>

</div>

<div class=”grid col-4 grid-square flex-sub”>

<div *ngIf=”productInfo1 == null || productInfo1.length < 1″ bindtap=”ChooseVideo” class=”solids”

(click)=’presentAction()’>

<span class=”cuIcon-add”></span>

</div>

</div>

</div>



ok,完成




版权声明:本文为Right__原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。