Upload Files To A Remote Server Using Ionic Framework

I was recently asked by one of my subscribers if I knew how to upload files from an Android or iOS device to a remote server using Ionic Framework.  My initial response was no, but it didn’t stop me from taking a whack at it.

Using the AngularJS extension set, ngCordova, with Ionic Framework and the Apache Cordova File Transfer plugin, you can easily upload files to a remote server.

This tutorial assumes you already have a functional web application that accepts file uploads from different domains or platforms.  I will be using a locally hosted web application created with NodeJS and SailsJS, but I won’t be explaining it in this example.

Let’s start by creating a fresh Ionic project using our Terminal:

Note, if you’re not on a Mac, you cannot add and build for iOS.

We’ll be using ngCordova in this project to make our lives easier, so go ahead and download the latest release and copy the ng-cordova.min.js file into your www/js directory.

Open your index.html file and include the script so it looks something like the code below:

Notice the two highlighted lines above.  It is very important you put ng-cordova.min.js above the cordova.js script include otherwise none of this will work correctly.

Now crack open your js/app.js file because we need to alter the angular.module to support ngCordova:

We’re not done.  At this point we’ve finished including ngCordova into our project, but it is only an extension set to the real plugin.  We still need to install the Apache Cordova File Transfer plugin.  Run the following from your Terminal:

Time to start taking care of business.  Inside your js/app.js file, we are going to create a new controller with an upload() method.  It will look something like this:

We are going to follow the official File Transfer documentation pretty closely at this point.  First we need to construct our options object which is explained by the following:


Object Key Object Type Description
fileKey string The name of the form element
fileName string The name to use when saving the file on the server
httpMethod string The HTTP method to use
mimeType string The mime type of the data to upload
params object The set of key pairs to pass in the request
chunkedMode boolean Whether to upload the data in chunked streaming mode
headers object The map of header name and values

Most of the above information was taken from the official documentation.  Based on this information our options object will look like this:

Only thing left to do is submit the POST request that contains the image file:

A few things to note about the above line.  $cordovaFileTransfer.upload will return a promise.  In this particular scenario we will be using a file from the Android project’s assets directory.  It won’t exist in iOS.  I suggest you read my previous post on Apache Cordova files or further explore the File documentation for ngCordova if you want a more cross platform solution.  I am just keeping it simple in this example with the assets directory.

Our finished controller should look like this:

All that’s left is to create the front end for this.  Open your index.html file and add the following code:

The above code just creates a button that will be used for uploading the file.  Now earlier I said that I was using SailsJS as my locally hosted server.  Based on the code from the quickstart, my server will return the following upon a successful upload:

You can see how simple that was to get files uploaded.  A common use case might be if you’re trying to create the next Instagram.  You can have your users upload images and other media to your server directly from their device.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Mark Jagunap

    I tried it and it works great on a single upload. I’m just wondering how to do it on a multiple images upload. I tried doing it on an angular.foreach loop and for some reason only the last loop that it triggered the upload file and the other data on the array seemed to be bypassed.

    • What do your logs say? I assume an error is listed?

      Regards,

  • Siddhartha R

    How about uploading an image to Amazon S3?

  • sameera207

    HI Nic, First off , thanks for the great articles on ionic, I tried your above article with the combination of Camera. It works fine until I get the picture from the camera. After that, when I try to upload if , it gives me the error

    Error: Can’t find variable: FileTransfer

    Please have a look at my SO quetion (coz if I paste it here, it will be unreadable..)

    http://stackoverflow.com/questions/27962615/cordovafile-file-upload-error

    After some research on google, It seems to be like its only a problem to IOS. But any help would be much
    appreciated as I’m kinda stuck here now..

    keep up the good work, cheers

    sam

    • Three things:

      1. Did you install the FileTransfer Apache Cordova plugin? If so, can you remove it and re-add it in case it became corrupted (very possible)?
      2. From your StackOverflow it looks like you’re trying to use the FileTransfer to upload base64 image data because you had set your camera to return the DATA_URL. You probably want to be uploading from the FILE_URL, not DATA_URL
      3. I could be wrong, but based on seeing an IP in your logs you’re trying to use live-reload or some kind of serve command to test your project. If this is the case, I urge you to build your project instead and install it to your device or simulator. Serving and live-reloading works terrible when it comes to Apache Cordova plugins.

      Let me know if any of this helps.

      BTW, I appreciate that you didn’t try to paste your code in the comments section of my blog. I wish everyone would do as you did by posting on StackOverflow or GitHub.

      Regards,

      • sameera207

        Hi Nic,

        Thanks for the prompt reply, (You are right.. I’m using phonegap developer app with live reload ), Following is my progress (thanks to you..)

        I get the above error vanished (yey…), here is what I did

        1) destinationType : Camera.DestinationType.FILE_URL

        2) Stop the phonegap emulator live reload. by starting it as
        phonegap serve --no-autoreload

        So no error..

        But now it gives this error

        [phonegap] [console.log] {
        [phonegap] “code”: 3,
        [phonegap] “source”: “file:///var/mobile/Containers/Data/Application/4EE5718C-02DB-4DC5-9F7D-D393EA9039E8/tmp/cdv_photo_010.jpg”,
        [phonegap] “target”: “http://localhost:3001/images/”,
        [phonegap] “http_status”: null,
        [phonegap] “body”: null
        [phonegap] }

        and according to this SO answer, (http://stackoverflow.com/questions/19275268/phonegap-file-transfer-of-picture-fails-on-every-other-picture-error-code-3-wit), I added
        the header option as well,

        options = { fileKey:”avatar”,
        fileName:”image.png”,
        headers{Connection:”close”},
        chunkedMode:false,
        mimeType:”image/jpeg”
        }

        but still no luck, the same error .. (but I think I’m so close…). What could be me doing wrong here.. ?

        thanks again for the tutorial and help

        cheers

        • Please do not use any serve type commands. It is very important you build and install. When using Apache Cordova plugins, you are leveraging native device code. By using serve OR live-reload, you are accessing the application remotely and quite possibly skipping all the native stuff.

          Let me know your results after you build an APK and install it.

          Regards,

          • sameera207

            Hi Nic,

            Finally got it working (sending request to the server) by using the ios emulator. Thanks a lot for the help.

            However I had to change the line
            ‘sourceType : Camera.PictureSourceType.PHOTOLIBRARY,’

            to get the photo from library instead of getting it directly from the camera. (as camera doesnt work in ios emulator)

            On a slightly different note, Following is my workflow when developing a mobile app (with ionic) and I would appreciate your comments. Coz I’m very new to mobile development)

            1 ) Testing the app locally (I have a backend server running locally)

            * I use ionic server for the UI testing with CORS plugin installed

            * I use phonegap developer app/ ios emulator for testing things like saving, and things browser doesnt support like ‘camera, fblogin’

            2 ) Releasing the app (for beta users… thats me again..) (I have a hosted server running)

            * I use testflight(https://www.testflightapp.com/) for releasing

            Thanks a lot again

            cheers

            sam

          • Hey, I’m glad you got it working. Your workflow seems exactly how I would do it. Just make sure when you test on device, you’re building the binary and installing it.

          • sameera207

            Hi Nic,

            Sorry for the late reply. thanks a lot for helping out, your blog is really helping me out. Keep up the good work

            cheers

          • Thanks for the compliment!

  • Paresh

    Many many thanks. Work like awesome

  • uwmoroghe

    Hey Nic,

    I tried your example using Ionic, but each time I call the $cordovaFile.uploadFile the app (android) crashes. Any ideas?

    Thanks

    • What do your Android ADB logs say? If it crashes, there is certainly an error message in the logs. Please paste them in the comments.

      Regards,

    • jorisw

      This might be helpful: http://stackoverflow.com/a/8942802

      Also try taking a smaller photo (set targetWidth / targetHeight to something smaller when taking the photo).

  • Maxime Barbot

    Hi, thank you for you tutorial, it helped me a lot! However, I am still new in ionic and this type of technology and i am stuck on the uploadFile method as well.. I feel like i don’t really understand where the picture is supposed to be stored. I have my sails server running on http://192.168.56.1:1337 but once i click on the button, is crashes saying that uploadFile is not defined.

    I tried different things such as copying thigs

    $scope.uploadFile= function (req, res) {

    }

    This is my point, I don’t have any accesses or anything, I probably need a mangodb server on the top of sails running?? I feel confused …. I really would like to be able to host and manage pictures on a server using ionic and cordova.

    Thanks again for your help.

    • I think you may be confusing Sails and Ionic by merging them together. In my example I used Sails because it was a quick way for me to spin up a web server. You can use whatever you want, PHP, .Net, ect.

      The

      uploads the file as form data. Similar to $_FILE if you were using PHP. This means that the file will be stored to the filesystem of the server, not a database.

      This tutorial was aimed towards Ionic and Cordova with the expectation that you already had enough knowledge about web applications. I encourage you to research how to make a web application with Express, Sails, PHP, ect., before jumping back into this tutorial.

      Regards,

    • Maxime Barbot

      Thank for your answer. I am actually having a webserver hosted on a dedicated server, which runs php and mysql. I feel like i would be way more confident with mysql, what difference does it make ? Can i directly past the file on http://localhost/whatever ? And what about this uploadFile which gives me an error and is not recognized ? My objective is to be abble to upload an image, which is gonna be stored somewhere and then be able to randomly display pictures for people.

      Thanks again for your help.

      • Have you ever created a file uploader with PHP? For example you make a web form with an upload field.

        If not, you should probably start there before trying to do it in Ionic.

        Regards,

    • Codin

      Hey, it works, Just use “$cordovaFileTransfer.upload()” instead of “$cordovaFile.uploadFile()”, dont forget to DI the $cordovaFileTransfer in the controller.

  • Codin

    Hello, Nice tutorial,
    but there is a mistake, instead of “$cordovaFile.uploadFile()” it should be “$cordovaFileTransfer.upload()”. Spent hours debugging the issue, finally checked in ng-cordova.js, on line no 2529, there is function ‘upload’ registered under ‘$cordovaFileTransfer’ service, So you will have to include ‘$cordovaFileTransfer’ in your controller.

    • Good catch! It looks like breaking changes were introduced in ng-cordova since I had written this tutorial. Looks like they changed uploadFile with upload.

      I’ll update this tutorial to reflect in the very near future.

      Regards,

      • Codin

        Not just the ‘upload’, it has been moved to ‘$cordovaFileTransfer’ from just ‘$cordovaFile’

        • Yep, thanks!

          • jim

            Still hasn’t been changed. Learned the hard way 🙁
            Also, it bears repeating that your file data on the server end will be in “$_FILES[‘avatar’]”.

          • Time has been tight. I haven’t had a chance to change. Thanks for reminding me 🙂

          • chetan awate

            still its not working ,and i already mention $cordovaFileTransfer in controller so now whats wrong with it

          • Kalluri Pavankumar

            Hi Nic can i have ur mail ID?? I have some doubt regarding uploading files…

          • I don’t offer free private help, sorry. You’ll have to use the comments section of my blog or find help on Stack Overflow.

            Best,

          • Kalluri Pavankumar

            Hi Nic, I want to to store image in php webservices. How to retrieve the image we are sending in PHP webservices. In PHP we will use $_FILES[“KEY”],what is the key i need to use in php?

  • Phil Brockwell

    has anyone managed to upload to a rails db with paperclip?

    • I’m only a PHP and NodeJS user, but I’ll welcome anyone to chime in if they have the experience 🙂

      • Phil Brockwell

        OK. Your blogs are very useful, i think this is the third one I’ve used so far. What file type is $cordovaFileTransfer.upload actually posting in the params? Like what should I be configuring the server to accept?

        • Hi Phil, I’m using carrierwave for Rails which is not so different from paperclip. I’ve used Nic’s example to upload images and audio files. With both gems you can upload base64 files, which is what I used for images but for audio files I just transfered the complete file. I prepared a gist that might be able to help you: https://gist.github.com/Random-Primate/390833d7a950e6daa008.js

  • 創新就從思想開始

    Hi, thanks for the tutorial,
    I’ve seen your other post about using ionic with parse.com and wonder if you can upload camera image to parse.com?

    • I have no idea. I don’t use Parse anymore, sorry.

  • Bob Zhang

    Thanks a lot

  • I assume it’s possible to modify this code slightly to save images to an Amazon S3 server while simultaneously storing the images location along with other related data in firebase….(correct me if I’m wrong)

    I simply am not experienced enough with AWS, Ionic, Cordova, Angular, Firebase, etc, to figure out how to tie all the pieces together to properly save and serve images with S3 and Firebase.

    Have you got any input on that matter or any links to resources that may be helpful?

    • I believe the Amazon S3 platform has a RESTful API that you can use in the same fashion as this example I made. However, I don’t know the endpoints to the API.

      You might want to do a quick Google search for the API documentation as I know it is very possible.

      Regards,

  • Bhagyashree kulkarni

    Hello sir,
    Could you please help out in pushing 2D elements in ionic framework?
    I tried one but it is not working .Should I paste code here?
    Thanks.

    • I don’t know what you’re referring to. Please do not paste code in the comments. Paste your error log and a description of what you’re trying to accomplish.

      Regards,

      • Bhagyashree kulkarni

        Sir, I am new to Ionic Framework. I need to Fetch data from the table whose fields are service and url ,store as a two dimensional array and display.

        please have a look at my code

        http://stackoverflow.com/questions/31019566/two-dimensional-array-in-ionic-framework

        After some research, it seems that problem is in controller while storing elements. Any help would be much appreciated.

        Thanks

        • Asking questions in the comments section of a post is only appropriate if the questions relate to that post. Your question does not.

          Please direct any unrelated questions at my Twitter account.

          Regards,

          • Bhagyashree kulkarni

            Ok

            Thanks.

          • Anil Kumar

            can you please put your code in github

            Regards
            Anil Kumar

  • chetan awate

    i got error that

    ReferenceError: FileTransfer is not defined

    and my code is

    .controller(“ExampleController”, function($scope, $cordovaFileTransfer) {

    });

    can you plz sort it out for me…

    • Are you sure the FileTransfer plugin was installed?

      • chetan awate

        yes i am shure ,i installed both plugins for File and File transfer

        • What if you add the plugin like this instead?:

          cordova plugin add cordova-plugin-file-transfer

          Per the documentation, it should work fine. Something is not adding correctly on your end. If that doesn’t work, please add your full project to GitHub.

          Regards,

      • chetan awate

        i got same error that”file tranfer is not defined ” ,is there any other way to do it

  • chetan awate

    https://github.com/chetanawate

    check my project ,uploaded on github k

    • First off, you don’t want to do this:

      Use one, not both.

      Second, when I ran your code I received no plugin related errors. Your upload logic is completely wrong, but it won’t throw any plugin or platform related errors.

      Based on this, you have configuration problems and logic problems that you need to address. I suggest you re-read my tutorial to fix your logic issues. I cannot help you anymore with configuration issues.

      Regards,

  • Hi Nic,

    Very useful article. Worked the uploading .png for me. But when I try to upload a pdf it fails.
    My options are as follows:
    var options = {
    fileKey: “sampledoc”,
    fileName: “sampledoc.pdf”,
    chunkedMode: false,
    mimeType: “application/pdf”
    };

    Would you be able to help me on this?

    Thanks in advance.

  • Zeeshan Ahmad

    Hello Nic,

    how to upload multiple images using cordovaFileTransfer.upload ? I want to upload three camera images and some other Json data in one RestApi ..

  • Prince

    Hello Nic,
    How we can upload files to Amazon S3 using Ionic Framework .??

  • carlos espitia

    Hello, Nice tutorial,

    Can I send video files?

  • andreainfusino

    Hello Nic, i’m developing a simple app in ionic and i need to upload a csv file to a php script that extracts the contained data. The user is asked to upload the file from his mobile device to the server. So i followed your tutorial and i got a strange issue: when i send the file to the server the filePath includes “C:fakepath” then i’m warned with a failure message that says: << “exception”: “URI not supported by CordovaResourceAPI: Cfakepathmyfile.jpg” >>, and http_status is 200 (i suppose is the server status, where i’m going to upload the file for php processing). I cannot solve it, and i can’t understand where’s the mistake. I read some workarounds on stackoverflow, telling to change device settings, but i think this is not a good solution for such a simple activity like sending a file to a server…! Thanks in advance and congrats for your work and great articles!
    Cheers from italy 🙂

    • I’m not sure why you have “C” in your path. Is “Cfakepathmyfile.jpg” the path on your device or your server?

      You should be using relative paths on your device or using the file commands to obtain the paths. For your server you should be trying to communicate over an address that your server is serving. Whether that be a locally hosted server like http://localhost, or something else.

      Hopefully that clears things up?

      • andreainfusino

        Hello Nic, thank you for you quick and detailed answer 🙂
        Maybe i was not clear in my answer, so i’ll try again. C:etc is the path from device: i put an input=file on my ionic app and i retrieve it’s value with javascript (while ng-model seems not working for this particular input type) and alerting while app is run on device, i get C:etc… I read surfing on it that this is a security issue, solved by provinding the fakepath string to avoid accessing the real path of device file system. But… i cannot believe no one can send a file from it’s device. Otherwise i have to create an user area on a website, but i wanted to avoid different user panels and maintaining only app functionalities. In addition: the server waiting for the file is not, obviously, a localhost but a real website (http:www.ricettario.info) where i put some php classess and interfaces for REST functionalities (user access, user data and options, CRUD operations, etc…)
        Thank you again!

  • Carlsson Zeit

    Thank’s for good tutorial. And i have questation, please help. When i click to download button, i get the message “ReferenceError: $cordovaFile is not defined”.

  • ykarthik reddy

    Hi Nic,

    I’m developing ionic app in IOS

    Image URI i’m getting is

    file:///var/mobile/Applications/5EF87D4D-9B4F-4D70-8B16-17C34CD10CA2/tmp/cdv_photo_001.jpg

    var options = {

    fileKey: “resources”,
    fileName:imageLink.substr(imageLink.lastIndexOf(‘/’)+1),
    chunkedMode: false,
    mimeType: “image/*”,
    httpMethod:”POST”,
    headers: {
    “X-Auth-Token”:token,
    “X-AppKey”:appkey
    }
    };

    $cordovaFileTransfer.upload(url, “file:///var/mobile/Applications/5EF87D4D-9B4F-4D70-8B16-17C34CD10CA2/tmp/cdv_photo_001.jpg”, options).then(function(result) {
    console.log(“SUCCESS: ” + result);
    }, function(err) {
    console.log(“ERROR: ” + JSON.stringify(err));
    });

    I’m getting the error here saying that

    {“success”:false,”status”:500,”msg”:”Supported types are are [image/png, image/jpeg, image/pjpeg, image/gif, image/jpg]. Ignoring files cdv_photo_001.jpg as they dont match valid extensions”,”errors”:[]}”,”exception”:null}

    The image which I try to upload has jpg extension, eventhough it is saying the above error.. Is there anything Which I’m doing wrong.

    Thankyou.

    • Are you sure that image is not corrupt? A MIME-TYPE is not the same as an extension. You can give any file a JPG extension, but that doesn’t mean it is a JPG file.

      Regards,

      • ykarthik reddy

        Thankyou for your reply.

        I’m using ngcordova camera plugin.. I’m taking the image using camera and getting the FILE_URI . Then passing it to upload. This is what I’m doing.. Will image corrupt in these process??

        • Is your error coming from your server or the plugin? Maybe your server is rejecting the file? Try specifying image/jpg as your mimeType instead of a wildcard.

          Honestly your code seems fine and that error message doesn’t seem concerning. My guess is you’re having server issues, or there is a bug in the plugin itself.

          • ykarthik reddy

            Hi Nic,

            Thankyou for your suggestions.

            I removed the image/* and made it to image/jpg, and it is working now..
            I had small doubt..
            I want to upload 5 images at a time.. Is there any possibility to upload all of them at once
            Like i need to pass 5 imageURL’s at once and get the response for every Individuals.

            Thankyou

          • The file transfer plugin only supports one file at a time. You’ll have to make several requests via your application.

            Regards,

          • ykarthik reddy

            Thankyou nic..

  • Anil Kumar

    Hi Nic ,
    how to find the path of the file , if I am accessing from external via input tag in html, Please have a look at my code I have posted in github: https://github.com/anilkumar007/File_Transfer

  • Brian

    Hi, I have tried your sample, then I have tried others with FileTransfer but none of them worked for more than 2 times. The first time I’ve implemented this, it worked fine. From the second time onwards, I keep receiving error code 3. I tried quite a lot of fixes, such as: headers = { Connection: ‘close’}, chunkedMode: false, reducing the quality of the image to 50, 10, 40 and so on, I have also tried with a new FileTransfer() object without using $cordovaFileTransfer and finally, I have tried to use another approach: Took the URL of the image, converted to base64, converted to file and sent as a normal post. Not even this approach worked.

    To consider, my C# Web API works fine. I receive the message, but there is no file in it. I assume FileTransfer is not sending the file together with my request when I try to upload.

    I have also tried to downgrade to version File Transfer version 0.4.8, as suggested in some post. But this also did not work for me.
    I am testing my code over an IOS simulator, any idea on how to fix this? I am up for a workaround if FileTransfer doesn’t show to be reliable enough.

    Snippet from my code:

    controller.js

    // Take the picture and save URI into $localStorage

    $scope.showAction = function() {

    // FileTransfer on button clicked
    var parameters = { “Username” : $localStorage.username };
    var options = {

    • Is this Xcode 7 with iOS 9 by chance?

      • Brian

        Yes it is!And have updated all plugins as well as phone gap

        • Brian

          As a little update, I figured that the upload works if I use one particular image from the default one in the library. Other images don’t 🙁

          • Not saying this is for sure the reason, but iOS 9 and Xcode 7 are having a ton of issues with Apache Cordova applications.

            What do you mean by “… one particular image from the default one in the library”? Maybe I am misunderstanding what you’re doing vs what you’re trying to do.

            Regards,

  • Renan Rosa

    Hello Nic!

    I’m having issues with the server side.
    Could you please send me the code of the server?

    Thx!

  • Renan Rosa

    Hello Nic!

    I’m having issues with the server side.
    Could you please send me the code of the server?

    Thanks!

    • This was not intended to be a server article. It assumes you already have working knowledge of creating server side code to handle uploads.

      With that said, I recommend a few Google searches on the server language of your choice.

      Best,

  • Ariel Montero

    Hello Nic thanks for your post. I have a problem using a PHP server. I have this functions

    };

    $scope.upload = function(file) {

    var options = {

    };

    console.log(‘va por aqui’);

    $cordovaFileTransfer.upload(URLUPLFILES, file, options).then(function(result) {

    }

    And my php looks like this

    But i don’t have response of my server

  • Saras

    hello Nic, I have tried your tutorial. I am getting error : ReferenceError: FileTransfer is not defined

    i have installed the plugins correctly these are plugins installed

    com.ionic.keyboard 1.0.4 “Keyboard”

    cordova-plugin-appsee 2.1.53 “Appsee”

    cordova-plugin-camera 1.2.0 “Camera”

    cordova-plugin-console 1.0.1 “Console”

    cordova-plugin-datepicker 0.8.5 “DatePicker”

    cordova-plugin-device 1.0.1 “Device”

    cordova-plugin-facebook4 1.3.0-0 “Facebook Connect”

    cordova-plugin-file 3.0.0 “File”

    cordova-plugin-file-transfer 1.4.0 “File Transfer”

    cordova-plugin-geolocation 1.0.1 “Geolocation”

    cordova-plugin-googleplayservices 19.0.3 “Google Play Services for Android”

    cordova-plugin-googleplus 4.0.3 “Google+”

    cordova-plugin-inappbrowser 1.0.1 “InAppBrowser”

    cordova-plugin-network-information 1.0.1 “Network Information”

    cordova-plugin-screen-orientation 1.4.0 “Screen Orientation”

    cordova-plugin-splashscreen 2.1.0 “Splashscreen”

    cordova-plugin-whitelist 1.0.0 “Whitelist”

    cordova-plugin-x-toast 2.2.0 “Toast”

    nl.x-services.plugins.calendar 4.3.6 “Calendar”

    nl.x-services.plugins.socialsharing 4.3.19 “SocialSharing”

    onesignal-cordova-plugin-pgb-compat 1.9.1 “OneSignal Push Notifications PGB Compat”

    org.apache.cordova.dialogs 0.3.0 “Notification”

  • figen önün

    Hello Nic thank you for your good tutorial,

    but when I use it in my project I got this eror,

    “ReferenceError: FileTransfer is not defined”

    and my eror log like this ;

    at Object.upload (http://localhost:8100/js/ng-cordova.min.js:8:7195)

    • Am I accurate when I assume you’re using ionic serve, ionic view, or ionic live-reload? If I am accurate, you need to stop using those services. They do not work correctly with plugins.

      • Operating Thetan

        What should we use instead?

        • Compile the app and install directly to a device or simulator.

          • Operating Thetan

            Ok, I’ll try it on my phone but the process is slower than live reload on browser when a file is changed.

            Do you think this feature could one day be avalaible on browser preview?

          • Well you’re building mobile applications, not web applications. Your development process and build process should treat them as such. Treating your mobile applications as web applications will only lead you down a path of problems.

            Regards,

  • miguel987654

    Hi thank for the tutorial.

    but i have this error

    {“code”:1,”source”:”http://127.0.0.1/mb_uploads/images/minah.jpg”,”target”:”http://127.0.0.1/mb_uploads/upload.php”,”http_status”:null,”body”:null,”exception”:null}

    1 = FileTransferError.FILE_NOT_FOUND_ERR

    any ideas?

    • Well it says the file was not found. What is the full path to the file you’re trying to upload and does it truly exist at that path?

      • miguel987654

        thanks for the reply, but the path file was wrong. Im working in IOS

        and work with this

        var url = “http://127.0.0.1/mb_uploads/upload.php”;
        var targetPath = cordova.file.documentsDirectory + “test.jpg”;

        .
        .
        .

        anyway thanks.

        sorry for my bad english

  • Alessandro Macagno

    Hi Nic! Really nice tutorial, could you do one with NativeScript? I’m stuck in uploading, and I don’t know how to solve this!

  • Tony

    Hi Nic, is there any way to secure this data transfer? If someone get to app source code, he can easily see that url (http://192.168.56.1:1337/file/upload) and make upload from some other script than your mobile app. How to make POST, or in this example img transfer, only from mobile app?

    Data is not that sensitive, and there is no need for https, but I just want to protect that script on server side from unauthorized access.

    • You need to create your own server side auth that uses tokens. This way when you sign into the application, you are returned with an API token which you will then pass with every request, whether it be upload or something else. No valid token means no valid upload.

      Without auth you won’t be able to guarantee access prevention from third party applications.

      • Tony

        Great, could you please point me to some basic example that use your suggestion?
        Thank you!

        • I have no examples to share sorry. You may want to read up on Oauth.

  • ZiLang

    How to upload through api instead of a page? I don’t know how to create a req.files object without using .

  • Rohan Shah

    can i use firebase for all type of file upload?
    if yes then how?

  • Julio Campos

    and if I would want to send the image to the Amazon S3 server, how I could do?

  • Tony Woo

    Hi Nic, Nice tutorial,

    I see you have hard code the target “”/android_asset/www/img/ionic.png”” there. How to allow user to select a file to upload in Cordova? Thanks.

  • gugasevero

    As always, nice tutorial Nic.
    I have a chat app and I want to take picture or get it from the photo library to send in the chat. How can I do that?
    I find out this tutorial “https://devdactic.com/complete-image-guide-ionic/”, very good too, but this part of my question, doesn’t have.

  • Krazzie KAy

    hey nice tutorial. can you explain the same for IOS devices too. Please reply.

    • Ionic Framework is cross platform. This tutorial should work fine for both Android and iOS.

  • Mohan Gopi

    Hi nic, I am not able to understand the field which is in options object, what is filekey,filename,chunkedMode,params… etc i am having a username and password to my ftp server how to give username and password .

    • This tutorial is for HTTP requests, not FTP. The options are essentially things you would set if you were uploading via a website form.

      • Mohan Gopi

        oh sorry nic, i am doing FTP sample project in which i need to send the image to FTP imediatly after taking the picture i have searched in google but i am not able to understand. So i followed ngcordova file transfer , how to do it is there any way if you like to suggest me to follow any blog…etc

  • Tony

    Hi Nic, I’m using your example and it’s working great. But now I need to upload multiple images at once. How to do that?
    Thank you!

    • I believe you need to do them one at a time. I don’t think the Apache Cordova plugin supports multiple file uploads.

  • Abhi Kureshi

    “Mr. Nic” I have an error of this type
    “FileTransfer.upload

    We seem to be missing some stuff 🙁

    What is kinda cool though you can fill in the textarea to pass a json object to the callback you want to execute”

    please resolve this

  • Yo Meyers

    Hi Nic.
    What if ii have a few heavy photos to upload, on IOS, will it upload them in the background also if the user will minimize the app?
    thanks

    • To my knowledge it will not upload in the background. You’d have to show a please wait indicator so people don’t navigate away.

  • Shweta Singhal

    Hi. I am using this plugin to transfer file from device to Google Drive. It transferred successfully and worked great. but file name after uploading is “Untitled”. I tried to pass file name, also tried to set meta data in params object but nothing worked. Can you please help me?

  • Abhishek

    Hi Nic,i’m new to hybrid app and I am facing a problem when i try to upload jpg image the image crashed in the server.Science we are hard-coding the mimeType , ‘image/png’, only png images is allowed to upload but not jpg.
    How to upload all types of images

  • Francisco Perez Duran

    and the “Apache Cordova File Transfer” plugin -> aim to a 404 page, which makes me doubt if anything else is obsoleted also. It loosks the plugin has been updated and I am not sure if the tutorial is still valid. Can you confirm us?

  • gobi c

    Hello Nic Raboy,
    Thanks for your tutorial, Its pretty awesome.
    But Need to know how to upload the pdf or doc file to remote server using Ionic Framework.
    can you pls explain about this pdf or doc file upload.

    Regards,
    Gobi

  • Dylane Ebang

    Hi
    I am following you from every where you can be on the net. I really appreciate your tutorials, there are verry helpful for my knowledges..
    Therefore, I have a little issue in what concerns firebase:
    Indeed, I’m developping an app for my society using ionic, google maps and firebase. In my database (firebase) I just store
    coords of a given position. But I’d like to match the position with images stored in firebase.
    How should I proceed please ?

    • Your question is not relevant to this article. Please find a relevant article and comment there, or take your question to Stack Overflow.

      Best,

  • Thanks for tutorial, I found some simple & useful article for uploading images to php server with PhoneGap http://phonegappro.com/tutorials/upload-images-to-server-using-phonegap-file-transfer-plugin/

  • chintakindi abhinav

    Thank you very much Nick Raboy!

    I was uploading my Images & videos . It work fine for images but not for videos… Searched a lot for solutions but only here I got the solution to set var options = {
    chunkedMode: true,
    mimeType: “video/mp4”
    };

    for cordovaFileTranfer .

  • Ajay Saini

    Hi,

    I am not able to upload image to server if imag BASE 64 SIZE is greater than 10 Mb.

    • You might try configuring your web server to accept uploads larger than 10MB. Sounds like a server side issue based on the information you’ve given me.

      Best,

      • Ajay Saini

        I am able to upload image (jpeg,png) to server if image size is greater than or less than10 MB. only problem is that when i crop image it gives base 64 image url. if this url is less than 10 MB then i upload base 64 image url successfully to server. but if this url is greater than 10 MB. then i am not able to upload base64 image url to server.

        • Sounds like your problem isn’t with file uploads then since you’re not uploading files. Sending base 64 data is nothing more than a RESTful HTTP request and isn’t relevant to the goal of this tutorial.

          • Ajay Saini

            why i am able to upload base 64 image url if size is less than 10 MB. ?

  • Leon Gautier

    Hi! The github page at the top of your blog is not available anymore :O
    is there anyway to install the cordova into our project? Thanks!

  • mubashar shahzad

    “cordova plugin add org.apache.cordova.file-transfer” returned 404…alternate r any available solution?

    • Nurdiana Bakri

      I have same problem, how ti fix them ?

      • mubashar shahzad

        you can use “cordova plugin add cordova-plugin-file-transfer” instead of “cordova plugin add org.apache.cordova.file-transfer”

  • Gopinath Kaliappan

    Hi How to upload image … from android device

  • Divya Eficaz

    Hello Nic,
    Very good article. But I got an error like this..
    “Error: FileTransfer is not defined
    .[email protected]://localhost:8100/js/ng-cordova.min.js:8:10353
    [email protected]://localhost:8100/js/app.js:34:9
    [email protected]://localhost:8100/lib/ionic/js/ionic.bundle.js line 27643 > Function:2:206
    @http://localhost:8100/lib/ionic/js/ionic.bundle.js:65429:9……”
    Can you help me for finding out the issue as I am new to Ionic…

    Thanks
    Divya

    • Anil Kumar

      Hi,
      You are uploading the file in localhost (http://localhost:8100/) and i think you are testing in web browser .. you have to test the above scenario in mobile devices with a valid server url.
      Regards,
      Anil Kumar

      • Divya Eficaz

        Hi,
        Thank you.
        Is there any problem occur while we try to access a server with ssl certified. I have uploaded the file normal server with the code, but while I tried for a https url its not working. Can you please help me.

        • Anil Kumar

          Hi,
          If you are going to use https .. than server people need to install SSL certificates and your error will be rectified.

          Regards,
          Anil Kumar

  • venis

    I am trying upload GIF file which has animation. But after uploading it appears as static gif without animation.
    I used mimeType: “image/gif” and fileName: “image.gif” , but it doesn’t worked.
    Please help me or suggest me with a solution

  • JC

    Can I send Any type of files using this?

  • kumar aditya

    Hi Nic,can I get more information about the image upload parameter,
    Like I have parameters of user_id, auth_key and image_pathname,
    Where exactly image parameter I can add in file upload function.