1.安装依赖包
npm install --save @ionic-native/camera //手机照相机功能
npm install --save @ionic-native/file //手机查找文件功能
npm install --save @ionic-native/file-path //文件路径功能
npm install --save @ionic-native/transter //文件传输功能
**2.添加插件
ionic cordova plugin add cordova-plufin-camera --save
ionic cordova plugin add cordova-plufin-file --save
ionic cordova plugin add cordova-plufin-file-transfer --save
ionic cordova plugin add cordova-plufin-filepath --save
ionic -g page headface
<!--
Generated template for the HeadfacePage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<ion-title>设置头像</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<img src="{{pathForImage(lastImage)}}" alt="" style="width:100%" [hidden]="lastImage === null" />
<h3 [hidden]="lastImage !== null">请从图片库选择图片</h3>
</ion-content>
<ion-footer>
<ion-toolbar color="primary">
<ion-buttons>
<button ion-button icon-left (click)="presentActionSheet()">
<ion-icon name="camera"></ion-icon>选择...
</button>
<button ion-button icon-left (click)="uploadImage()" [disable]="lastImage === null">
<ion-icon name="cloud-upload"></ion-icon>上传
</button>
</ion-buttons>
</ion-toolbar>
</ion-footer>
import { Component } from '@angular/core';
import { IonicPage, normalizeURL, NavController, NavParams, ActionSheetController, ModalController, LoadingController, Platform, ToastController, ViewController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { BaseUI } from '../../common/baseui';
import { RestProvider } from '../../providers/rest/rest';
//导入四个外部加载进来的组件
import { File } from '@ionic-native/file';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { FilePath } from '@ionic-native/file-path';
import { Camera } from '@ionic-native/camera';
declare var cordova: any; //导入第三方的库定义到ts项目中
/**
* Generated class for the HeadfacePage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@Component({
selector: 'page-headface',
templateUrl: 'headface.html',
})
export class HeadfacePage extends BaseUI {
userId: string;
errorMessage: string;
lastImage: string = null
constructor(public navCtrl: NavController,
public navParams: NavParams,
public actionsheetCtrl: ActionSheetController,
public modalCtrl: ModalController,
public loadCtrl: LoadingController,
public rest: RestProvider,
public storage: Storage,
public camera: Camera,
public transfer: Transfer,
public file: File,
public filePath: FilePath,
public platform: Platform,
public toastCtrl: ToastController,
public viewCtrl: ViewController) {
super()
}
ionViewDidLoad() {
this.storage.get('UserId').then((val) =>{})
}
presentActionSheet() {
let actionSheet = this.actionsheetCtrl.create({
title: '选择图片',
buttons: [
{
text: '从图片库中选择',
handler: () => {
this.takePicture(this.camera.PictureSourseType.PHOTOLIBRARY)
}
},
{
text: '使用相机',
handler: () => {
this.takePicture(this.camera.PictureSourseType.CAMERA)
}
},
{
text: '取消',
role: 'cancel'
}
]
});
actionSheet.present();
}
takePicture(sourseType) {
//定义相机的一些参数
var options = {
quality: 100, //图片质量
sourceType: sourceType,
savaeToPhotoAlbum: false, //是否保存拍摄的照片到相册中去
correctOrientation: true //是否纠正拍摄的照片的方向
};
//获取图片的方法
this.camera.getPicture(options).then((imagePath) => {
//特别处理android平台的文件路径问题
if (this.platform.is('android') && sourseType === this.camera.PictureSourseType.PHOTOLIBRARY) {
this.filePath.resolveNativePath(imagePath) //获取android平台下的真实路径
.then(filePath => {
//获取正确的路径
let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
//获取正确的文件名
let correctName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'))
this.copyFileToLocalDir(correctPath, correctName, this.createFileName())
});
} else {
//获取正确的路径
let correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
//获取正确的文件名
let correctName = imagePath.substr(imagePath.lastIndexOf('/') + 1)
this.copyFileToLocalDir(correctPath, correctName, this.createFileName());
}
}, (err) => {
super.showToast(this.toastCtrl, "选择图片出错,请在APP中操作或检查权限")
});
}
//将获取到的图片或者相机拍摄到的图片进行下另存为,用于后期的图片上传使用
copyFileToLocalDir(namePath, currentName, newFileName) {
this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
this.lastImage = newFileName;
}, error => {
super.showToast(this.toastCtrl, "存储图片到本机图库出现错误")
});
}
//为文件生成一个新的文件名
createFileName() {
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg"; //拼接文件名
return newFileName;
}
public pathForImage(img){
if(img === null){
return '';
} else {
//refer
return normalizeURL(cordova.file.dataDirectory + img);
}
}
//上传的参数
uploadImage(){
var url = 'https://imoocqa.gugujiankong.com/api/account/updateheadface';
var targetPath = this.pathForImage(this.lastImage);
var filename = this.userId + ".jpg"; //定义上传后的文件名
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
mimeType: "multipart/form-data",
params: { 'fileName': filename, 'userid': this.userId }
};
const fileTransfer: TransferObject = this.transfer.create();
var loading = super.showLoading(this.loadCtrl,"上传中...");
//开始正式地上传
fileTransfer.upload(targetPath,url,options).then(data=>{
loading.dismiss();
super.showToast(this.toastCtrl,'图片上传成功。');
//在用户看清弹窗提示后进行页面的关闭
setTimeout(()=>{
this.viewCtrl.dismiss()
},3000);
},err=>{
loading.dismiss();
super.showToast(this.toastCtrl,'图片上传出错。');
})
}
}