"Introduction to Features"
In the development of the application, often encounter the need to upload images, such as modifying the profile picture. This article describes the function of uploading images on the mobile side based on the Ionic framework.
"Function Flow"
(1) Click on the picture on the page, pop up a dialog box, select [Take photos] or [choose from the album];
(2) Select/take photos;
(3) Upload photos;
"HTML Core Code"
< Div ng-controller= "Myctrl" > < ng-click= "Choosepicmenu ()"> <ng-src = "{{img}}"> </a></ Div >
"Myctrl.js Core Code"
(1) Function of image selection
Define the function that selects the photo,
$scope. Choosepicmenu =function () {
var type = ' gallery ';
$ionicActionSheet. Show ({
Buttons: [
{text: ' Take Pictures '},
{text: ' Select from album '}
],
TitleText: ' Select Photos ',
Canceltext: ' Cancel ',
Cancelfunction () {
},
ButtonClicked:function (index) {
if (index = = 0) {
Type = ' camera ';
}else if (index = = 1) {
Type = ' gallery ';
}
//camera.getpicture (type) is selected according to the selection of "Pick picture"
Camera.getpicture (Type). Then (
//Returns a Imageuri that records the path of the photo
function (Imageuri) {
$scope. Me. image = Imageuri;
Update photos on a page
$scope. img = Imageuri;
$scope. $apply ();
},
function (Err) {
});
return true;
}
});
};
(2) Core code in the upload function
//New file Upload option, and set file 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";
//Use params to save other parameters such as nickname, age, etc.
var params = {};
params[' name '] = $scope.Me.Name;
//Add params to the params of the options
Options.params = params;
//New Filetransfer object
var ft =New Filetransfer ();
//Upload files
Ft.upload (
$scope.me.image,
encodeURI (' some URL '), //sends pictures and other parameters to this URL, which is equivalent to a request to receive pictures and other parameters in the background and then process
Uploadsuccess,
Uploaderror,
options);
//upload Successful words
function uploadsuccess (r) {
var resp = Json.parse (R.response);
if (Resp.status = = 0) {
//return to previous page
$ Navhistory.back ();
}else{
$ionicPopup. Alert ({
title: ' Message ',
CssClass: ' Alert-text ',
Template: ' Upload fail! '
});
}
}
//upload failed
function Uploaderror (Error) {
}
Extended:
Here is an article to upload and download using the Ng-cordova file transfer plugin->http://santoshshinde2012.blogspot.sg/2015/03/ File-upload-download-with-ng-cordova.html
ZH cheese: Ionic+angularjs+cordova (filetransfer) upload image "mobile side"