ionic3 调用本地相册并上传图片

前言

  在APP中启动相册选择器或者拍照上传图片这些功能是非常常见的。对于Ionic2,我们只能通过cordova插件实现调用原生的功能。下面将简单的封装一个选择相册或拍照上传图片的ImgService服务。具体如下。

Cordova准备

  下载安装所需的Cordovar插件: 
Image Picker(相册选择)

ionic plugin add https://github.com/Telerik-Verified-Plugins/ImagePicker
  • 1

Camera(拍照)

ionic plugin add cordova-plugin-camera
  • 1

Transfer(上传文件)

ionic plugin add cordova-plugin-file-transfer
  • 1

ImgService服务的实现

  通过显示ActionSheet组件,让用户选择上传图片的方式,如从相册选择或者拍照。具体如下:

/*** Created by admin on 2016/10/21.*/
import { Injectable } from "@angular/core";
import { ActionSheetController } from "ionic-angular";
import { Camera, ImagePicker, Transfer } from "ionic-native";
import { NoticeService } from "./notice.service";@Injectable()
export class ImgService {// 参考:https://github.com/driftyco/ionic-native/blob/master/src/plugins/camera.ts// 调用相机时传入的参数private cameraOpt = {quality: 50,destinationType: 1, // Camera.DestinationType.FILE_URI,sourceType: 1, // Camera.PictureSourceType.CAMERA,encodingType: 0, // Camera.EncodingType.JPEG,mediaType: 0, // Camera.MediaType.PICTURE,allowEdit: true,correctOrientation: true};// 调用相册时传入的参数private imagePickerOpt = {maximumImagesCount: 1,//选择一张图片width: 800,height: 800,quality: 80};//imgPath: string = ''; //图片路径fileTransfer: Transfer;upload: any = {url: 'http://xxx/',           //接收图片的urlfileKey: 'image',  //接收图片时的keyheaders: {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' //不加入 发生错误!!},params: {},        //需要额外上传的参数success: (data) => {}, //图片上传成功后的回调error: (err) => {},   //图片上传失败后的回调listen: () => {}   //监听上传过程};constructor(private actionSheetCtrl: ActionSheetController,private noticeSer: NoticeService) {}showPicActionSheet() {this.useASComponent();}// 使用ionic中的ActionSheet组件private useASComponent() {let actionSheet = this.actionSheetCtrl.create({title: '选择',buttons: [{text: '拍照',handler: () => {this.startCamera();}},{text: '从手机相册选择',handler: () => {this.openImgPicker();}},{text: '取消',role: 'cancel',handler: () => {}}]});actionSheet.present();}// 使用原生的ActionSheet组件/*private useNativeAS() {let buttonLabels = ['拍照', '从手机相册选择'];ActionSheet.show({'title': '选择','buttonLabels': buttonLabels,'addCancelButtonWithLabel': 'Cancel',//'addDestructiveButtonWithLabel' : 'Delete'}).then((buttonIndex: number) => {if(buttonIndex == 1) {this.startCamera();} else if(buttonIndex == 2) {this.openImgPicker();}});}*/// 启动拍照功能private startCamera() {Camera.getPicture(this.cameraOpt).then((imageData) => {this.uploadImg(imageData);}, (err) => {this.noticeSer.showToast('ERROR:' + err); //错误:无法使用拍照功能!});}// 打开手机相册private openImgPicker() {let temp = '';ImagePicker.getPictures(this.imagePickerOpt).then((results) => {for (var i = 0; i < results.length; i++) {temp = results[i];}this.uploadImg(temp);}, (err) => {this.noticeSer.showToast('ERROR:' + err); //错误:无法从手机相册中选择图片!});/*let str = '{"status":1,"msg":"提示:图片上传成功!","data":"http:\/\/192.168.1.20\/image\/580af6bcc4d40580af6bcc4d45.jpg"}';let res = JSON.parse(str);this.upload.success(res);*/}// 上传图片private uploadImg(path: string) {if(!path) {return;}this.fileTransfer = new Transfer();let options: any;options = {fileKey: this.upload.fileKey,headers: this.upload.headers,params: this.upload.params};this.fileTransfer.upload(path, this.upload.url, options).then((data) => {if(this.upload.success) {this.upload.success(JSON.parse(data.response));}}, (err) => {if(this.upload.error) {this.upload.error(err);} else {this.noticeSer.showToast('错误:上传失败!');}});}// 停止上传stopUpload() {if(this.fileTransfer) {this.fileTransfer.abort();}}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172

  注:这里自定义了一个NoticeService服务,主要用于统一toast的显示。如下:

/*** Created by Administrator on 2016/10/10 0010.*/
import { Injectable }     from '@angular/core';
import { ToastController } from 'ionic-angular';@Injectable()
export class NoticeService {static TOAST_POS_BOTTOM: string = 'bottom';static TOAST_POS_MIDDLE: string = 'middle';constructor(private toastCtrl: ToastController) {}// 显示 toast提示showToast(message: string, position: string = NoticeService.TOAST_POS_BOTTOM) {let toast = this.toastCtrl.create({message: message,duration: 1500,position: position});toast.present();return toast;}/*showNoticeByToast(code: Number, msg: string) {let m = '';if(code == 1) {m = '提示:' + msg + '!';} else {m = '错误' + code + ':' + msg + '!';}return this.showToast(m);}*/showNoticeByToast(code: Number, msg: string) {let m = '';if(msg && msg.length > 0) {if(msg.charAt(msg.length - 1) == '!' || msg.charAt(msg.length - 1) == '!') {msg = msg.substr(0, msg.length - 1);}}if(code == 1) {m = '提示:' + msg + '!';} else {m = '错误' + code + ':' + msg + '!';}return this.showToast(m);}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

ImgService服务的使用

  使用ImgService服务,需要在对应的Page页面中的构造方法中进行注入。如:

constructor(private notiSer: NotiService,private imgSer: ImgService) {}
  • 1
  • 2
  • 3

  使用ImgService服务,需要我们先进行初始化,如:

// 初始化上传图片的服务private initImgSer() {this.imgSer.upload.url = ''; // 上传图片的url,如果同默认配置的url一致,那无须再设置this.imgSer.upload.success = (data) => {//上传成功后的回调处理};this.imgSer.upload.error = (err) => {this.noticeSer.showToast('错误:头像上传失败!');};}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

  正式使用:

this.initImgSer();
this.imgSer.showPicActionSheet();
  • 1
  • 2

示例效果

  Android显示效果如下: 
ImgService服务的使用

相册选择器的汉化

  在打开相册选择器的过程中,我们可能会发现其相册选择器的“取消”或“确定”按钮是英文显示的。但是BOSS可能会要求我们修改为中文,这时又要伤一下脑筋咯。 
  解决(针对Anroid来说,ios应该也是一样滴):在项目的plugins目录下找到com.synconset.imagepicker文件夹,进入src/android/Library/res目录,创建values-zh文件夹,在values-zh文件夹中创建multiimagechooser_strings_zh.xml文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources><string name="multi_app_name">图片选择器</string><string name="free_version_label">免费版本 - 剩余图片: %d</string><string name="error_database">打开相册出现错误.</string><string name="requesting_thumbnails">请稍后...</string><string name="processing_images_header">图像选择</string><string name="processing_images_message">这可能是一个短暂的瞬间的时间.</string><string name="maximum_selection_count_error_header">Auswahllimit erreicht</string><string name="maximum_selection_count_error_message">Sie können maximal %d Bilder auf einmal auswählen.</string><string name="discard">取消</string><string name="done">确定</string>
</resources>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

  修改plugins/com.synconset.imagepicker/plugin.xml文件,找到android区域,增加如下语句:

<source-file src="src/android/Library/res/values-zh/multiimagechooser_strings_zh.xml" target-dir="res/values-zh"/>


需要的插件(ionic 官网 native中均有):

$ ionic cordova plugin add cordova-plugin-file $ npm install --save @ionic-native/file $ ionic cordova plugin add cordova-plugin-file-transfer $ npm install --save @ionic-native/file-transfer $ ionic cordova plugin add cordova-plugin-camera $ npm install --save @ionic-native/camera $ ionic cordova plugin add cordova-plugin-telerik-imagepicker --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="需要访问您的相册" $ npm install --save @ionic-native/image-picker

  • 1

  删除项目platforms文件夹下的android平台,重新添加平台打包运行即可。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/387171.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Mapreduce中maptask过程详解

一、Maptask并行度与决定机制 1.一个job任务的map阶段的并行度默认是由该任务的大小决定的&#xff1b; 2.一个split切分分配一个maprask来并行处理&#xff1b; 3.默认情况下&#xff0c;split切分的大小等于blocksize大小&#xff1b; 4.切片不是mapper类中对单词的切片&…

4 开发MapReduce应用程序

系统参数配置 Configuration类由源来设置&#xff0c;每个源包含以XML形式出现的一系列属性/值对。如&#xff1a; configuration-default.xml configuration-site.xml Configuration conf new Configuration(); conf.addResource("configuraition-default.xml"…

实用的HTML5的上传图片方法

<input type"file" accept"video/*;capturecamcorder"> <input type"file" accept"audio/*;capturemicrophone"><input type"file" accept"image/*;capturecamera">直接调用相机<input type…

3.11 列出完数

完数&#xff1a;一个数恰好等于不包括自身的所有不同因子之和。如6123。 输入&#xff1a;每一行含有一个整数n。 输出&#xff1a;对每个整数n&#xff0c;输出所有不大于n的完数。输出格式为&#xff1a;整数n&#xff0c;冒号&#xff0c;空格&#xff0c;完数&#xff0…

angularjs 上传

xxx.module.ts模块 import { NgModule} from “angular/core”; import { FileUploadModule } from “ng2-file-upload” ; import { XXXComponent } from “./xxx.component”; NgModule({ imports:[ FileUploadModule ], declarations:[ XXXComponent &#xff0c;/component…

PHPCMS的产品筛选功能

如下图所示功能&#xff1a; 首先&#xff0c;用下面这些代码替换掉phpcms/libs/functions/extention.func.php的内容 <?php /*** extention.func.php 用户自定义函数库** copyright (C) 2005-2010 PHPCMS* license http://www.phpcms.cn/licen…

框架使用SpringBoot + Spring Security Oauth2 +PostMan

框架使用SpringBoot Spring Security Oauth2 主要完成了客户端授权 可以通过mysql数据库读取当前客户端表信息进行验证&#xff0c;token存储在数据库中 1.引入依赖 oauth2 依赖于spring security&#xff0c;需要引入spring&#xff0c; mysql&#xff0c;redis&#xff0c; …

3.12 12!配对

找出输入数据中所有两两相乘的积为12!的个数。 输入样例&#xff1a; 1 10000 159667200 9696 38373635 1000000 479001600 3 1 479001600 输出样例&#xff1a; 3 有3对&#xff1a; 1 479001600 1 479001600 3 159667200 #include<iostream> #include<fstre…

程序员自身价值值这么多钱么?

xx 网络公司人均奖金 28 个月…… xx 科技公司人均奖金 35 个月…… 每到年底&#xff0c;这样的新闻在互联网业内简直是铺天盖地。那些奖金不高的程序员们一边羡慕嫉妒&#xff0c;一边暗暗比较一下自己的身价&#xff0c;考虑是不是该跳槽了。 不同水平的程序员&#xff0c;薪…

3.13 判读是否是对称素数

输入&#xff1a;11 101 272 输出&#xff1a; Yes Yes No #include<fstream> #include<iostream> #include<sstream> #include<string> #include<cmath> using namespace std;bool isPrime(int); bool isSymmetry(int);int main(){ifstream…

Spring MVC中使用 Swagger2 构建Restful API

0.Spring MVC配置文件中的配置[java] view plaincopy<!-- 设置使用注解的类所在的jar包&#xff0c;只加载controller类 --> <span style"white-space:pre"> </span><context:component-scan base-package"com.jay.plat.config.contro…

Go语言规范汇总

目录 统一规范篇合理规划目录GOPATH设置import 规范代码风格大小约定命名篇基本命令规范项目目录名包名文件名常量变量变量申明变量命名惯例全局变量名局部变量名循环变量结构体(struct)接口名函数和方法名参数名返回值开发篇包魔鬼数字常量 & 枚举结构体运算符函数参数返回…

3.14 01串排序

将01串首先按照长度排序&#xff0c;其次按1的个数的多少排序&#xff0c;最后按ASCII码排序。 输入样例&#xff1a; 10011111 00001101 10110101 1 0 1100 输出样例&#xff1a; 0 1 1100 1010101 00001101 10011111 #include<fstream> #include<iost…

platform(win32) 错误

运行cnpm install后&#xff0c;出现虽然提示不适合Windows&#xff0c;但是问题好像是sass loader出问题的。所以只要执行下面命令即可&#xff1b;方案一&#xff1a;cnpm rebuild node-sass #不放心可以重新安装下 cnpm install方案二&#xff1a;npm update npm install no…

Error: Program type already present: okhttp3.Authenticator$1

在app中的build.gradle中加入如下代码&#xff0c; configurations {all*.exclude group: com.google.code.gsonall*.exclude group: com.squareup.okhttp3all*.exclude group: com.squareup.okioall*.exclude group: com.android.support,module:support-v13 } 如图 转载于:ht…

3.15 排列对称串

筛选出对称字符串&#xff0c;然后将其排序。 输入样例&#xff1a; 123321 123454321 123 321 sdfsdfd 121212 \\dd\\ 输出样例 123321 \\dd\\ 123454321 #include<fstream> #include<iostream> #include<string> #include<set> using …

ES6规范 ESLint

在团队的项目开发过程中&#xff0c;代码维护所占的时间比重往往大于新功能的开发。因此编写符合团队编码规范的代码是至关重要的&#xff0c;这样做不仅可以很大程度地避免基本语法错误&#xff0c;也保证了代码的可读性&#xff0c;毕竟&#xff1a;程序是写给人读的&#xf…

前端 HTML 常用标签 head标签相关内容 script标签

script标签 定义JavaScript代码 <!--定义JavaScript代码--> <script type"text/javascript"></script> 引入JavaScript文件 src""引入的 js文件路径 <!-- 引入JavaScript文件 --> <script src"./index.js"></s…

3.16 按绩点排名

成绩60分及以上的课程才予以计算绩点 绩点计算公式&#xff1a;[(课程成绩-50) / 10 ] * 学分 学生总绩点为所有绩点之和除以10 输入格式&#xff1a; 班级数 课程数 各个课程的学分 班级人数 姓名 各科成绩 输出格式&#xff1a; class 班级号: 姓名&#xff08;占1…

iview日期控件,双向绑定日期格式

日期在双向绑定之后格式为&#xff1a;2017-07-03T16:00:00.000Z 想要的格式为2017-07-04调了好久&#xff0c;几乎一天&#xff1a;用一句话搞定了 on-change”addForm.Birthday$event”<Date-picker placeholder"选择日期" type"datetime" v-model&…