In this tutorial I will discuss how to upload file in a remote server using ionic framework & php. First of all ionic is a great framework where we can make app which supported in both platform. And there are so many plugins in cordova which supported in ionic framework & we can create something special by using cordova plugins. Let’s start the main topic. Just follow my steps.
Step 1:
First of all we need a plugin for uploading file and that is Apache Cordova File Transfer plugin. Just install it through the terminal/cmd by using bellow command.
cordova plugin add cordova-plugin-file-transfer
Step 2:
Now we need to create a view in ionic. And I already created a html content just attach it.
<!-- start view --> <ion-view view-title="Add Image" name="add-image"> <ion-content> <img ng-src="{{pathForImage(image)}}" style="width: 100%; height: 100%;"> </ion-content> <ion-footer-bar class="bar bar-positive"> <div class="button-bar"> <button class="button icon-left ion-camera" ng-click="loadImage()">Take Photo</button> <button class="button icon-left ion-upload" ng-click="uploadImage()" ng-disabled="image === null">Upload</button> </div> </ion-footer-bar> </ion-view> <!-- end view -->
Step 3:
Now we have to create it’s related contrller in a js file. Insert the bellow code into a js file.
angular.module('starter').controller('uploadController',function($scope, $cordovaCamera, $cordovaFile, $cordovaFileTransfer, $cordovaDevice, $ionicPopup, $cordovaActionSheet,$localstorage,$ionicLoading,$state,$http,ionicToast){ $scope.image = null; $scope.showAlert = function(title, msg) { var alertPopup = $ionicPopup.alert({ title: title, template: msg }); }; $scope.loadImage = function() { var options = { title: 'Select Image Source', buttonLabels: ['Load from Library', 'Use Camera'], addCancelButtonWithLabel: 'Cancel', androidEnableCancelButton : true, }; $cordovaActionSheet.show(options).then(function(btnIndex) { var type = null; if (btnIndex === 1) { type = Camera.PictureSourceType.PHOTOLIBRARY; } else if (btnIndex === 2) { type = Camera.PictureSourceType.CAMERA; } if (type !== null) { $scope.selectPicture(type); } }); }; $scope.selectPicture = function(sourceType) { var options = { quality: 100, destinationType: Camera.DestinationType.FILE_URI, sourceType: sourceType, saveToPhotoAlbum: false }; $cordovaCamera.getPicture(options).then(function(imagePath) { var currentName = imagePath.replace(/^.*[\\\/]/, ''); var d = new Date(), n = d.getTime(), newFileName = n + ".jpg"; if ($cordovaDevice.getPlatform() == 'Android' && sourceType === Camera.PictureSourceType.PHOTOLIBRARY) { window.FilePath.resolveNativePath(imagePath, function(entry) { window.resolveLocalFileSystemURL(entry, success, fail); function fail(e) { console.error('Error: ', e); } function success(fileEntry) { var namePath = fileEntry.nativeURL.substr(0, fileEntry.nativeURL.lastIndexOf('/') + 1); $cordovaFile.copyFile(namePath, fileEntry.name, cordova.file.dataDirectory, newFileName).then(function(success){ $scope.image = newFileName; }, function(error){ $scope.showAlert('Error', error.exception); }); }; } ); } else { var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1); $cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success){ $scope.image = newFileName; }, function(error){ $scope.showAlert('Error', error.exception); }); } }, function(err){ }) }; $scope.pathForImage = function(image) { if (image === null) { return ''; } else { return cordova.file.dataDirectory + image; } }; $scope.uploadImage = function() { var url = "http://localhost/test/upload.php"; var targetPath = $scope.pathForImage($scope.image); var options = { fileKey: "file", fileName: filename, chunkedMode: false, mimeType: "multipart/form-data" }; $ionicLoading.show({ template : "Please wait...." }); $cordovaFileTransfer.upload(url, targetPath, options).then(function(result) { $ionicLoading.hide(); //success or error result }); } })
Step 4:
If everything is all right up to previous step now we come to the 4th step. And here we need a remote server to test this. We can use localhost as a remote server. So make a project in wamp/xamp/lamp/mamp, named it “test”. Inside the project folder create a php file named it “upload.php”. Now attach the bellow code on it. Also create a folder inside the “test” folder and named it “uploads”.
<?php header('Access-Control-Allow-Origin: *'); $target_path = "uploads/"; $target_path = $target_path . basename( $_FILES['file']['name']); if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) { echo "Upload and move success"; } else{ echo "There was an error uploading the file, please try again!"; } ?>
Now try to check the project by uploading a file. If everything is okay then your file will be uploaded successfully & you will get it inside the “uploads” folder.
Can u tell me in step 3 where is file which i can add code js ?
If you create seperated js file for all of your controller then create another js file named it “uploadController.js”. Then insert the code in to this file.
Thanks you! Nice TUT