How to make uploading files or images using ionicframwork or angularJS


is any one got success to read the file size in onSuccess method after selecting file from gallery and before uploading to server.I am getting only file url in onSuccess method.

I wants to display the file size and actual file name with extention.Even i am not getting extention also only file url getting in onSuccess method like -

$scope.takePic = function() {
        var options =   {
            quality: 50,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: 0,      // 0:Photo Library, 1=Camera, 2=Saved Photo Album
            encodingType: 0     // 0=JPG 1=PNG
    var onSuccess = function(FILE_URI) {
       //How to get file size and actual file name heare
    var onFail = function(e) {
        console.log("On fail " + e);


You will probably just need to add the extension to the name yourself. You know the extension based on the encodingType you specified. Default is JPG.

function resolveLocalFileSuccessHandler(fileEntry) { 
    fileEntry.getMetadata(function(metadata) {
         alert(metadata.size); // or do something more useful with it..

 $window.resolveLocalFileSystemURL(FILE_URI, resolveLocalFileSuccessHandler);


Hi Keithmoore,how and where we can we call resolveLocalFileSuccessHandler method or it will call automatically…

As i add it within controller but its not calling.


I would suggest that you add an error handler to the function. And define that error handler. Maybe something like this…

function resolveLocalFileErrorHandler(error) {

$window.resolveLocalFileSystemURL(FILE_URI, resolveLocalFileSuccessHandler, resolveLocalFileErrorHandler); 


Thanks its working but still i am getting file name as number not the actual file name.



This is expected behavior. You might have a look at this:
I have not used it, but it might help you.


I am running into issues trying to implement this and will appreciate any help I can get.

My problem is that the DestinationType object is throwing an error as undefined “Cannot read property ‘FILE_URI’ of undefined”.

Is there something I am not getting right?



I successfully implemented this with an Express server and ngCordova.

Install this plugin

cordova plugin add org.apache.cordova.file-transfer

Then I used this code

var options =   {
    quality: 100
    , destinationType: Camera.DestinationType.FILE_URI
    , sourceType: Camera.PictureSourceType.PHOTOLIBRARY
    , encodingType: Camera.EncodingType.JPEG


	function(fileURL) {

		var uploadOptions = new FileUploadOptions();
		uploadOptions.fileKey = "file";
		uploadOptions.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
		uploadOptions.mimeType = "image/jpeg";
		uploadOptions.chunkedMode = false;

		$cordovaFile.uploadFile(<path to your server api>, fileURL, uploadOptions).then(
			function(result) {
				// Success!
			}, function(err) {
				// Error



I used the multer npm module on my Express server to handle the file upload.
Of course this won’t work in the browser, only on a device.

Ionic to aws s3 image upload

Even better, I just built a service to do this so that it’s easily reusable elsewhere.


You are using this option:

options.fileKey = "post";

However, this option ist backend-specific. I took me a long time to figure it out.

just remove the property if you don’t want this



You can upload images or any other files in two possible methods:

  1. Convert it to BASE64 string and upload it to the server via REST call.
  2. Directly upload binary file to server using ngCordova File Transfer plugin

The second solution is usually a better one because it doesn’t require additional processing power required to convert binary data to BASE64 string. Use the first method only if you specifically need BASE64 representation.

ngCordova File Transfer plugin can be used like this:

// Destination URL, you can use other technologies beside PHP
var url = "";
//File for Upload
var targetPath = cordova.file.externalRootDirectory + "someFile.png";
// File name only
var filename = targetPath.split("/").pop();
var options = {
	 fileKey: "file",
	 fileName: filename,
	 chunkedMode: false,
	 mimeType: "image/jpg",
         params : {'directory':'upload', 'fileName':filename} // directory represents remote directory,  fileName represents final remote file name
 $cordovaFileTransfer.upload(url, targetPath, options).then(function (result) {
	 console.log("SUCCESS: " + JSON.stringify(result.response));
 }, function (err) {
	 console.log("ERROR: " + JSON.stringify(err));
 }, function (progress) {

params is most important parameter here because it will tell server side where to store uploaded file(s).

Here’s an example of server-side PHP code:

	header('Access-Control-Allow-Origin: *');
	$location = $_POST['directory'];
	$uploadfile = $_POST['fileName'];
	$uploadfilename = $_FILES['file']['tmp_name'];
	if(move_uploaded_file($uploadfilename, $location.'/'.$uploadfile)){
			echo 'File successfully uploaded!';
	} else {
			echo 'Upload error!';

###Click here for a working example



Hi @Gajotres,

Can I transfer file from img source? I am setting the cropped image to a hidden img as follows:

<div><img data-ng-src="data:image/jpeg;base64,{{myCroppedImage}}" ng-hide="true" id="image"/></div>

Best Regards.


Hi Sebastian,

Can u please share your html page of above mentioned controller, that would be a great favor.
Thanks in advance.


hi @Sebastian , the ionic code is really working it hit my server side code right , but i am missing something , can you please share your server side code if it is in express.js


can you please share the express server side code


Hey @nurfarazi in your main node file use the multer library to upload your files.

Their documentation should get you on your way :smile:


i tried multer but i don’t know something not right , i am posting my code can you please check.

var express = require('express');
var http = require('http');
var multer = require('multer');
var bodyParser = require('body-parser');
var multerS3 = require('multer-s3');
var aws = require('aws-sdk');
var app = express();

limit: '50mb'
limit: '50mb',
extended: true

app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");

var storage = multer.diskStorage({

destination: function (req, file, callback) {
    callback(null, './uploads');
    console.log('hit storage');
filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' +;
    console.log('hit storage');

var upload = multer({
storage: storage
}).single('userPhoto');'/upload2', function (req, res) {
console.log('hit post');
upload(req, res, function (err) {
    if (err) {
        return res.end("Error uploading file.");
    } else {
        res.end("File is uploaded");


you can simply copy and paste the above code in server.js and test . and by the my ionic code is given below

angular.module('starter.controllers', ['ngCordova'])

.controller('DashCtrl', function ($scope, $cordovaCamera, $cordovaFileTransfer, $http) {

  $scope.takePic = function () {
    var options = {
        quality: 50,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: 0, // 0:Photo Library, 1=Camera, 2=Saved Photo Album
        encodingType: 1 // 0=JPG 1=PNG
    }, onFail, options);

var onSuccess = function (FILE_URI) {
    $scope.picData = FILE_URI;
    //$scope.picData = LZString.compressToUTF16(FILE_URI)

var onFail = function (e) {
    console.log("On fail " + e);

 $scope.send = function () {

    var options = {
        fileName: $scope.picData.substr($scope.picData.lastIndexOf('/') + 1),
        chunkedMode: false,
        mimeType: "image/png"

    $cordovaFileTransfer.upload('http://localhost:8001/upload2', $scope.picData, options).then(function (result) {
            console.log("SUCCESS: " + JSON.stringify(result.response));
        function (err) {
            console.log("ERROR: " + JSON.stringify(err));
        function (progress) {


the above code is complete controller code , so you dont have to worry about , can you please help me with this .

and the error i get is this

{ [Error: Unexpected field]
  field: 'file',
  storageErrors: [] }

FYI: i use chrome inspect device feature to run the localhost in my android .

another thing, why i am getting image url like this
> “content://”

formate missing , does it make any sense ?


please provide server side upload code. If anyone has working code please share with me.
I am trying to select image form gallery and upload with php
@yafraorg I have refer your code but there is no server side file available pls share with us .

Thank You.



Hi sebastian i am not able to understand the options object and i am also trying to do the file transfer but i invoke only error call not success call i am not sure what i am doing wrong please help me if you find any error.

i have posted my question in stack overflow but no reply .

here is my controller and services part

  var imgPath = [];

  this.getImgPath = function(){
    return imgPath;
  this.setImgPath = function(path){
    imgPath = path ;



  $scope.takePicture = function(){

    var options = { 
            quality : 75, 
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.CAMERA,
            allowEdit : false,
            encodingType: Camera.EncodingType.JPEG,
            mediaType: Camera.MediaType.PICTURE,
            targetWidth: 250,
            targetHeight: 250,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: false

        $cordovaCamera.getPicture(options).then(function(imageURI) {
          console.log('invokeing cordovaCamera');
          $scope.image =  imageURI;
        }, function(err) {
            // An error occured. Show a message to the user

    $scope.upload =function(){

      var options = {
         fileKey: "file",
         fileName: "gopi",
         chunkedMode: false,
         mimeType: "image/jpeg",
         params : {'user_token':'Chandru@123', 'user_email':'wepopusers'} // directory represents remote directory,  fileName represents final remote file name
      $cordovaFileTransfer.upload('',  MyService.getImgPath(), options)
        .then(function(result) {
          // Success!
          console.log("SUCCESS: " + JSON.stringify(result.response));
          alert('ftp success');
        }, function(err) {
          // Error
          alert('ftp fail');
          console.log("ERROR: " + JSON.stringify(err));
        }, function (progress) {
          // constant progress updates



Hi Sebastian, I was able to upload the files to the server (node server) and now I deployed my server in heroku, but I was not able to upload the file when the server is running in heroku. Its because heroku does not provide storage space for storing files or images at run time. I noticed that you have used the heroku platform and can you help me with how did you solve this issue. Any help would be appreciated. :slight_smile: