Upload an Image to the Php Server Using Ionic
Capturing, storing and uploading images with Ionic is one of the most used functions. Everyone wants to take photos and work with them inside their app, but in my previous guide about using images with Ionic many people encountered problems on Android. Others needed a backend to upload images. And the code is a bit outdated equally well.
So in this tutorial we volition see how to take a photo or load one from the library, copy that image inside our app binder and finally upload it to a very unproblematic PHP server. In this tutorial nosotros will use Ionic one due to the high demand, but if you lot desire an Ionic ii app for this case besides please leave a comment below!
Let's get the fun started, this is a existent hands-on project and you could take the lawmaking every bit a starter for many other projects.
Prerequisite
Learning Ionic tin can get overwhelming, I know that feeling. Is learning from tutorials and videos sometimes non enough for you? So I got something for you lot.
If you desire to larn Ionic with step-by-step video courses, hands-on training projects and a helpful community who has your back, then have a look at the Ionic Academy.
Setup the Ionic Image Upload Project
We first with a bare Ionic 1 app and install a handful of Cordova plugins we demand to access the camera, the filesystem and and so on. Boosted we install ngCordova, the Angular 1 wrapper for Cordova plugins.
ionic outset devdactic - prototype - upload blank cd devdactic - image - upload # Add Cordova Plugins ionic plugin add cordova - plugin - file ionic plugin add cordova - plugin - file - transfer ionic plugin add cordova - plugin - filepath ionic plugin add together cordova - plugin - photographic camera ionic plugin add cordova - plugin - actionsheet # Install ngCordova bower install ngCordova -- save |
After setting up our project we need to load the ngCordova lib inside the caput section of our index.html before the cordova.js file:
<script src = "lib/ngCordova/dist/ng-cordova.js" > </script> |
Finally make sure to add together the ngCordova dependency to the array of dependencies of our app inside the world wide web/app.js:
angular . module ( 'starter' , [ 'ionic' , 'ngCordova' ] ) |
Now nosotros got a solid amount of plugins and stuff for our app. Note that we demand to test this app within the simulator or a device as we need native functionality, so make sure to add the platform (iOS/ Android) you need to your project.
Creating a uncomplicated view
The view of our Ionic image upload app volition be very simple. We just need 2 buttons for loading an image and uploading it afterwards. We also want to display the file nosotros took within the app merely to make sure we have the correct i. Go ahead and open the alphabetize.html and supersede the electric current body with this:
<body ng-app = "starter" ng-controller = "ImageCtrl" > <ion-pane> <ion-header-bar class = "bar-positive" > <h1 class = "title" > Devdactic Image Upload </h1> </ion-header-bar> <ion-content> <img ng-src = "{{pathForImage(prototype)}}" style = "width: 100%; height: 100%;" > </ion-content> <ion-footer-bar class = "bar bar-positive" > <div grade = "push-bar" > <button class = "button icon-left ion-photographic camera" ng-click = "loadImage()" > Take Photograph </push> <button class = "button icon-left ion-upload" ng-click = "uploadImage()" ng-disabled = "epitome === null" > Upload </button> </div> </ion-footer-bar> </ion-pane> </body> |
Zero actually special, just note that we will resolve the actual path to the image using a function. By doing this nosotros could e'er get the path right even afterwards appstart. In this example we are not storing the epitome, but if you plan to y'all would just have to shop the name of the image and the path to the app folder will always be added.
We will encounter how this works later, for at present e only need a little implementation of our ImageCtrl
and so open the www/app.js and add together:
. controller ( 'ImageCtrl' , part ( $ scope , $ cordovaCamera , $ cordovaFile , $ cordovaFileTransfer , $ cordovaDevice , $ ionicPopup , $ cordovaActionSheet ) { $ scope . image = nix ; $ telescopic . showAlert = role ( title , msg ) { var alertPopup = $ ionicPopup . alert ( { title : title , template : msg } ) ; } ; // The rest of the app comes in here } ) ; |
As you can encounter, we load quite a agglomeration of dependencies here. We volition see them in action later, for now we only have our empty scope paradigm and a office to display an alert. Permit's continue with the funny office!
Loading camera or library images into our Ionic app
Earlier nosotros actually capture the image, we desire to present the user a elementary actionsheet to select betwixt using the camera and loading an image from the photograph library. We already installed the needed cordova plugin, so at present nosotros simply implement our function to prove the actionsheet:
1 2 3 4 v 6 7 8 ix ten 11 12 13 14 fifteen sixteen 17 18 xix twenty | // Present Actionsheet for switch beteen Camera / Library $ scope . loadImage = function ( ) { var options = { championship : 'Select Image Source' , buttonLabels : [ 'Load from Library' , 'Use Camera' ] , addCancelButtonWithLabel : 'Abolish' , androidEnableCancelButton : truthful , } ; $ cordovaActionSheet . show ( options ) . and so ( office ( btnIndex ) { var type = nothing ; if ( btnIndex === 1 ) { type = Camera . PictureSourceType . PHOTOLIBRARY ; } else if ( btnIndex === 2 ) { type = Camera . PictureSourceType . CAMERA ; } if ( type !== naught ) { $ scope . selectPicture ( blazon ) ; } } ) ; } ; |
We need to specify some options which we then tin can pass to the $cordovaActionSheet
. When the user selects one of those two options, we telephone call our actual paradigm taking part with the specified source type.
The actionsheet volition await like this on iOS.
This is our next part, and the biggest ane of this tutorial as well. Actually the code is only that long because we have special treatment for Android with photo library, all other cases already work with i function of the function.
I am not completely sure why we need this, but afterward long testing I found this solution to be working on iOS and Android with Camera and library every bit well, so if yous had problems earlier, this lawmaking might ready it.
Then first of all add the code, and we will come across how it works below the snippet:
1 ii 3 4 5 6 7 8 9 10 11 12 xiii fourteen 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 | // Take image with the camera or from library and shop it within the app folder // Image will not be saved to users Library. $ scope . selectPicture = function ( sourceType ) { var options = { quality : 100 , destinationType : Photographic camera . DestinationType . FILE_URI , sourceType : sourceType , saveToPhotoAlbum : false } ; $ cordovaCamera . getPicture ( options ) . and then ( role ( imagePath ) { // Catch the file proper name of the photo in the temporary directory var currentName = imagePath . replace ( / ^ . * [ \ \ \ / ] / , '' ) ; //Create a new name for the photograph var d = new Date ( ) , northward = d . getTime ( ) , newFileName = n + ".jpg" ; // If you are trying to load image from the gallery on Android we need special handling! if ( $ cordovaDevice . getPlatform ( ) == 'Android' && sourceType === Camera . PictureSourceType . PHOTOLIBRARY ) { window . FilePath . resolveNativePath ( imagePath , function ( entry ) { window . resolveLocalFileSystemURL ( entry , success , neglect ) ; function fail ( e ) { console . error ( 'Mistake: ' , e ) ; } function success ( fileEntry ) { var namePath = fileEntry . nativeURL . substr ( 0 , fileEntry . nativeURL . lastIndexOf ( '/' ) + 1 ) ; // Simply copy because of access rights $ cordovaFile . copyFile ( namePath , fileEntry . name , cordova . file . dataDirectory , newFileName ) . then ( function ( success ) { $ telescopic . prototype = newFileName ; } , function ( error ) { $ scope . showAlert ( 'Error' , fault . exception ) ; } ) ; } ; } ) ; } else { var namePath = imagePath . substr ( 0 , imagePath . lastIndexOf ( '/' ) + 1 ) ; // Motility the file to permanent storage $ cordovaFile . moveFile ( namePath , currentName , cordova . file . dataDirectory , newFileName ) . then ( part ( success ) { $ scope . image = newFileName ; } , function ( fault ) { $ scope . showAlert ( 'Error' , mistake . exception ) ; } ) ; } } , function ( err ) { // Not always an error, maybe cancel was pressed... } ) } ; |
The $cordovaCamera.getPicture
call starts the photo selection, either by starting the photographic camera or by opening the photo library. This part works fine, but now we actually want to copy that image from wherever it is currently to our app binder.
If we are at present on Android and accept selected the library as source type, we telephone call some functions to resolveNativePath
of the file, because the URL nosotros go from the picker won't work out of the box. Now we can resolve the right path to a local filesystem URL and finally $cordovaFile.copyFile
to the directory of our app.
We specify the cordova.file.dataDirectory, y'all can run into where those folders are on the ngCordova documentation for the File plugin.
The else function for all other cases is quite short compared to the special treatment, and nosotros do the same thing as above but now we can also call $cordovaFile.moveFile
equally we are allowed to move the file. In the previous section we could only re-create the file to our directory.
Finally, in both cases we apply just the filename to our $scope.image
variable, every bit we will resolve the rest of the URL with a function. Yous can add this office now:
// Returns the local path inside the app for an image $ scope . pathForImage = function ( paradigm ) { if ( image === null ) { render '' ; } else { return cordova . file . dataDirectory + image ; } } ; |
Nosotros simply render the directory of our app plus the image proper noun. If you plan to store the epitome names, you can do this and create the correct path after startup again. If you would store the whole path you might become into issues as the path to your app folder could change over time!
And then now nosotros are already able to load an image into our app. The next part handles the upload to a elementary PHP server.
If yous want to learn Ionic 1 in detail, brand sure to join my step-by-step course Ionic by Doing!
The epitome you lot cull should exist visible inside your app view similar in the image below.
Uploading our images from the App
The Ionic part for file upload is kinda easy. We need the URL to the server, the file and some parameters and then nosotros can telephone call $cordovaFileTransfer.upload
to upload our file.
Sounds piece of cake?
It is indeed, so go ahead and add the image upload part:
i 2 3 4 five vi vii viii 9 ten 11 12 13 xiv fifteen sixteen 17 18 19 twenty 21 22 | $ scope . uploadImage = function ( ) { // Destination URL var url = "http://localhost:8888/upload.php" ; // File for Upload var targetPath = $ scope . pathForImage ( $ scope . prototype ) ; // File name only var filename = $ scope . image ; ; var options = { fileKey : "file" , fileName : filename , chunkedMode : false , mimeType : "multipart/form-data" , params : { 'fileName' : filename } } ; $ cordovaFileTransfer . upload ( url , targetPath , options ) . and so ( function ( event ) { $ scope . showAlert ( 'Success' , 'Image upload finished.' ) ; } ) ; } |
Obviously you might accept to change the destination URL wherever your PHP server is. This tutorial won't be complete with a solution for that accepting role, then go ahead to create your little PHP backend!
Creating our simple image upload PHP server
I am not using PHP oft, simply many of you asked for a PHP solution and I constitute information technology quite like shooting fish in a barrel to setup this littler server to accept files. I am mostly more a fan of Firebase solutions as a Backend, but for this example PHP works perfectly.
If y'all have a server you can apply that one, otherwise I simply recommend to download XAMPP and install information technology local.
I'grand non going to cover that procedure since this is about Ionic image upload and not how to configure PHP. If you have fix information technology up, you tin kickoff of all create a upload.php to have uploads:
<?php header ( 'Access-Control-Permit-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 $target_path ; echo "There was an error uploading the file, please try again!" ; } ?> |
Too, make sure to create a uploads folder next to this file, every bit information technology volition copy the images into that binder.
Additionally, to see the results of our hard piece of work, I created a little HTML file that will scan the uploads folder and show them then we can directly see if our upload worked, Create this as index.php side by side to the previous file and insert:
1 2 3 4 5 half dozen 7 8 ix 10 11 12 xiii 14 xv 16 17 18 19 xx 21 22 | <!DOCTYPE html> <html> <head> <meta charset = "utf-viii" > <meta name = "viewport" content = "initial-scale=ane, maximum-calibration=one, user-scalable=no, width=device-width" > <title> Devdactic Image Upload </title> </caput> <torso> <h1> Ionic Image Upload </h1> <?php $browse = scandir ( 'uploads' ) ; foreach ( $scan every bit $file ) { if ( ! is_dir ( $file ) ) { echo '<h3>' . $file . '</h3>' ; repeat '<img src="uploads/' . $file . '" style="width: 400px;"/><br />' ; } } ?> </trunk> </html> |
At present you got everything in place and can kickoff your Ionic image upload adventures!
If you now option an image and upload it, yous should run into this dialog as a result (after finished upload).
Determination
There are many problems related to ionic prototype capturing, loading them to the app and using them later. This tutorials shows a way to bypass those issues on iOS and Android plus how to use the local files within your app to send them to a PHP server.
If you encounter problems or but like the tutorial, leave a comment below and share it with your boyfriend developers!
Happy Coding,
Simon
Source: https://devdactic.com/ionic-image-upload-php/
Postar um comentário for "Upload an Image to the Php Server Using Ionic"