Working example cordova FileTransfer plugin with Ionic 2 typescript

Hi all,

I am having troubles finding a good working example of usage of the cordova file transfer plugin. I’m not sure what to do exactly so if someone has a working example + step by step guide it would really help me out.

The only thing I had to do for example the Camera was install the plugins through

ionic plugin add cordova-plugin-camera

and then just import them in the .ts files like

import {Camera} from 'ionic-native';

This works well for these cordova plugins, but I can’t seem to get it to work with the cordova file transfer plugin.

I’ve tried installing the cordova typings with tsd install ionic cordova --save (not sure if needed, but having the typing is always good I think?). I’m able to reach the FileTransfer object in the platform.ready function but it doesn’t have the function on it that I think I need. And I’d really would want to use the FileTransfer in my PluginsService injectable.

1 Like

Have you solved this issue?

I have solved it partly. See this topic. I haven’t found a pretty ionic solution since the FileTransfer plugin is not a ionic native plugin yet.

Hey, I created a basic example here: https://github.com/dsgriffin/Ionic-2-File-Transfer-Example hope it helps.

3 Likes

Hi,

unfortunately you example wont work. Neither FileTransfer name can’t be found nor cordova. Do I missing something while trying to compile it?

Most likely - what error are you getting?

I get “Error TS2304: Cannot find name ‘cordova’” and “TS2304: Cannot find name ‘FileTransfer’”

Make sure Cordova is installed globally (I have 6.1.1), that adding platforms are working for the project etc.

Hmm, I have 6.11 installed globally too. Adding plugin via ionic plugin add cordova-plugin-file-transfer won’t help either. Any ideas what I’m missing?

Even if you get TypeScript errors, doing ionic build ios will still build the project which will work on the device itself. Ionic 2 and TypeScript together seem to have quite a few bugs (just like Ionic 2 + SASS) still

It makes quite difficult to write the code if error message is every time visible. I know the plugin suppose to work only on devices, but coding with errors is annoying. I don’t know what I’m doing wrong, but adding file-transfer plugin won’t work.

Any ideas what I can do just to download files and save it to the device storage? It’s really urgent for our current project.

True but that is a fault with TypeScript and Ionic, they are in Beta so still gonna be some issues.

Yes the plugin will not work on emulator or in browser, when you have done npm install and ionic build iOS, it will error but still build the iOS folder. The iOS folder does work and is tested so I need the exact error that is stopping you from running ionic build iOS successfully as I cannot reproduce your problem

Have you installed the typings?

First make sure you have the npm package installed

npm install -g typings

Then install the tsd files from the root of your app (CLI)

typings install cordova --save --ambient
typings install cordova/plugins/filetransfer --save --ambient
typings install cordova/plugins/filesystem --save --ambient

Typescript side should work then, I only have the FileUploadOptions wich it still gives an error about. Havent found a solution for that yet. But even with the error the code should be working just fine when deployed on your devices.

Many thanks! Finally got rid of all the error messages! :slight_smile:

No problem. Glad to help out :slight_smile:

I have a working UPLOAD example here for anyone who is interested. https://github.com/dtaalbers/FileTransferExample

You can use it how ever you want. Just know that it is not perfect (since FileTransfer is not yet ionic native). I know the jquery used to update the DOM elements with the upload progress isn’t pretty. I’ll take suggestion how to improve it :slight_smile:.

The pictures will be uploading to a staging API of mine. So know that I can see what you upload :smile:. To test if the API is working on not you can ping it by GET requesting this url http://services.dtaalbers.com/staging/ping.

2 Likes

@dsgriffin Sorry I have totally missed your example. My bad :neutral_face:

hey dtaalbers,
thank your for your good Upload Example. Tested it and it works well.
I have a problem at serverside to handle the data. You got an idea?

    [HttpPost("stage")]
    public object Stage(ICollection<IFormFile> filename)
    {
        if (filename.Count != 1) {
            return new BadRequestResult();
        } 
        ...

I can share what I am using. To be clear this is a WebApi2 Controller in ASP.NET C#

    [HttpPost, Route("pictures")]
    public async Task<IHttpActionResult> Post()
    {
        if (!Request.Content.IsMimeMultipartContent())
            return InternalServerError("UnsupportedMediaType");

        var provider = new CustomMultipartFormDataStreamProvider("absolute-path-to-save-image-to");

        try
        {
            // Load the stream into buffer
            Request.Content.LoadIntoBufferAsync().Wait();

            // Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
            await Request.Content.ReadAsMultipartAsync(provider);
        }
        catch (Exception ex)
        {
            return InternalServerError($"Failed buffer load: {ex.Message}");
        }

        // To get custom parameters from the request.
        var parameter = provider.FormData["MyParameterName"];

        // do stuff with your parameters
    }

For the CustomMultipartFormDataStreamProvider

/// <summary>
/// Used to override an action within the MultipartFormDataStreamProvider
/// This is needed to format the file name of a posted file
/// </summary>
internal class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string path) : base(path) { }

    /// <summary>
    /// Takes the bodypart off of the filename string
    /// </summary>
    /// <param name="headers">the headers to mutate</param>
    /// <returns>mutated filename</returns>
    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
    }
}

I hope it helps you!

1 Like

Had to bring the API down for a while. That means for now you can not upload to my API and because of that the FileTransferExample will return an error when uploading. If you want to upload your image to your own API you can change the URL here.