博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ionic3 打开相机与相册,并实现图片上传
阅读量:5324 次
发布时间:2019-06-14

本文共 4274 字,大约阅读时间需要 14 分钟。

 

安装依赖项等:

 

$ ionic cordova plugin add cordova-plugin-camera$ npm install --save @ionic-native/camera

 

创建ImgUploadProvider服务

import { Injectable } from "@angular/core";import { ActionSheetController } from "ionic-angular";import 'rxjs/add/operator/map';import { Camera,CameraOptions} from "@ionic-native/camera";import { ImagePicker ,ImagePickerOptions} from "@ionic-native/image-picker";import { AlertController } from "ionic-angular";import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';@Injectable()export class ImgUploadProvider {  avatar: string = "";  constructor(    private camera: Camera,    private alertCtrl:AlertController,    public actionSheetCtrl: ActionSheetController,    public imagePicker: ImagePicker,    private  fileTransfer: FileTransfer,  ){  }  upload(filePath,uploadUrl) {    let options: FileUploadOptions = {      fileKey: 'image',      fileName: 'name.jpg',      headers: {          api_token:"HBAPI@20180608jiangbei"      }      // .....    };    const fileTransfer: FileTransferObject = this.fileTransfer.create();    return  fileTransfer.upload(filePath, uploadUrl, options)      .then((data) => {        let alert =this.alertCtrl.create({          title:'上传成功!',          message:JSON.stringify(data),          buttons: ['确定'],        });        alert.present();        return data;      }, (err) => {        let alert =this.alertCtrl.create({          title:'上传失败!',          message:JSON.stringify(err),          buttons: ['确定'],        });        alert.present();      })  }  presentActionSheet() {    return new Promise((resolve,reject)=>{      let actionSheet = this.actionSheetCtrl.create({        buttons: [{          text: '拍照',          role: 'takePhoto',          handler: () => {            resolve('takePhoto');          }        }, {          text: '从相册选择',          role: 'chooseFromAlbum',          handler: () => {            resolve('chooseFromAlbum');          }        }, {          text: '取消',          role: 'cancel',          handler: () => {            console.log("cancel");          }        }]      });      actionSheet.present().then(value => {        return value;      });    })  }  chooseFromAlbum() {    const options: ImagePickerOptions = {      maximumImagesCount: 1,      quality: 100      // width: 200,      // height: 200    };    return this.imagePicker.getPictures(options).then(images => {      if (images.length > 1) {        this.presentAlert();      } else if (images.length === 1) {        this.avatar = images[0].slice(7);        // alert('Image URI: ' + images[0]);        return this.avatar;      }    }, error => {      console.log('Error: ' + error);    });  }  takePhoto() {    const options: CameraOptions = {      quality: 100,      allowEdit: true,      // targetWidth: 200,      // targetHeight: 200,      saveToPhotoAlbum: true,    };    return this.camera.getPicture(options).then(image => {      // console.log('Image URI: ' + image);      this.avatar = image.slice(7);      return this.avatar;    }, error => {      console.log('Error: ' + error);    });  }  presentAlert() {    let alert = this.alertCtrl.create({title: "上传失败", message: "只能选择一张图片作为头像哦", buttons: ["确定"]});    alert.present().then(value => {      return value;    });  }}

 在页面注入ImgUploadProvider服务:

import { ImgUploadProvider } from "../../providers/img-upload/img-upload"; // private imgUploadProvider:ImgUploadProvider,

调用:

private presentActionSheet(){    this.imgUploadProvider.presentActionSheet().then((res)=>{      if(res==="takePhoto"){        this.imgUploadProvider.takePhoto().then((res)=>{          this.avatar=res;          this.imgUploadProvider.          upload(res,this.service.BaseUrl+"/file/imageupload?api_token=your token")            .then((data:any)=>{              this.avatar=data.response.data[0];            })        });      }else if(res==="chooseFromAlbum"){        this.imgUploadProvider.chooseFromAlbum().then((res)=>{          this.avatar=res;          this.imgUploadProvider.upload(res,this.service.BaseUrl+"/file/imageupload?api_token=your token")            .then((data:any)=>{              this.avatar=data.response.data[0];            })          // alert(res);        });      }    });  }

 

转载于:https://www.cnblogs.com/mlh1421/p/10803095.html

你可能感兴趣的文章
<转>Shell脚本相关
查看>>
使用FreeMarker加载远程主机上模板文件,比如FTP,Hadoop等(转载)
查看>>
Java的位运算符具体解释实例——与(&amp;)、非(~)、或(|)、异或(^)
查看>>
java 注解 学习
查看>>
[leetcode]403. Frog Jump青蛙过河
查看>>
英语音节知识
查看>>
IEEE 802.15.4协议学习之MAC层
查看>>
AngularJS学习篇(十三)
查看>>
Tableau 学习资料
查看>>
中断和异常
查看>>
lucene 全文检索工具的介绍
查看>>
C# MD5-16位加密实例,32位加密实例
查看>>
无线点餐系统初步构思
查看>>
AJAX
查看>>
前端之CSS
查看>>
List注意点【修改】
查看>>
sqoop导入导出对mysql再带数据库test能跑通用户自己建立的数据库则不行
查看>>
拓扑排序的原理及其实现
查看>>
对StageWebView捕获位图时空白
查看>>
Provison Profile管理及存放路径
查看>>