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.pswp.cn/news/387171.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/387171.shtml
英文地址,請注明出處:http://en.pswp.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&…