ZH乳酪:ionic+angularJS+cordova(FileTransfer)上傳圖片【移動端】

來源:互聯網
上載者:User

標籤:

【功能介紹】

在開發應用的時候,經常會遇到需要上傳圖片的功能,比如修改設定檔的頭像。本文介紹的是基於ionic架構,在移動端上傳圖片的功能。

【功能流程】

(1)點擊頁面上的頭像,彈出一個對話方塊,選擇[拍照]或者[從相簿選擇];

(2)選取/拍攝照片;

(3)上傳照片;

【html核心代碼】

<div ng-controller="myCtrl">    <a ng-click="choosePicMenu()">        <img ng-src="{{img}}">    </a></div>

【myCtrl.js核心代碼】

(1)選取圖片的函數

//定義選擇照片的函數,
$scope.choosePicMenu = function() {
var type = ‘gallery‘;
$ionicActionSheet.show({
buttons: [
{ text: ‘拍照‘ },
{ text: ‘從相簿選擇‘ }
],
titleText: ‘選擇照片‘,
cancelText: ‘取消‘,
cancel: function() {
},
buttonClicked: function(index) {
if(index == 0){
type = ‘camera‘;
}else if(index == 1){
type = ‘gallery‘;
}
       //Camera.getPicture(type)->根據選擇的“選取圖片”的方式進行選取
Camera.getPicture(type).then(
          //返回一個imageURI,記錄了照片的路徑
function (imageURI) {
$scope.me.image = imageURI;
            //更新頁面上的照片
$scope.img = imageURI;
$scope.$apply();
},
function (err) {
});
return true;
}
});
};

 (2)上傳函數中的核心代碼

//建立檔案上傳選項,並設定檔案key,name,type
var options = new FileUploadOptions();
options.fileKey="ffile";
options.fileName=$scope.me.image.substr($scope.me.image.lastIndexOf(‘/‘)+1);
options.mimeType="image/jpeg";
//用params儲存其他參數,例如暱稱,年齡之類
var params = {};
params[‘name‘] = $scope.me.name;
//把params添加到options的params中
options.params = params;
//建立FileTransfer對象
var ft = new FileTransfer();
//上傳檔案
ft.upload(
$scope.me.image,
encodeURI(‘some url‘),//把圖片及其他參數發送到這個URL,相當於一個請求,在後台接收圖片及其他參數然後處理
uploadSuccess,
uploadError,
options);
//upload成功的話
function uploadSuccess(r) {
var resp = JSON.parse(r.response);
if(resp.status == 0){
     //返回前一頁面
$navHistory.back();
}else{
$ionicPopup.alert({
title: ‘Message‘,
cssClass: ‘alert-text‘,
template: ‘Upload fail!‘
});
}
}
//upload失敗的話
function uploadError(error) {
}

 擴充:

這裡有一篇文章,使用ng-cordova的file transfer外掛程式進行上傳和下載->http://santoshshinde2012.blogspot.sg/2015/03/file-upload-download-with-ng-cordova.html

ZH乳酪:ionic+angularJS+cordova(FileTransfer)上傳圖片【移動端】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.