Skip to content

Uploading through NativeScript (Angular)

Janko Marohnić edited this page Nov 18, 2019 · 1 revision

NativeScript allows you to use javascript either natively or through a framework such as React or Angular to create mobile apps. I wanted to send an image using nativescript to my Rails backend.

  1. Install nativescript-backend-http

    $ tns plugin add nativescript-background-http
    
  2. Configure Shrine for Direct Uploads

  3. Find your Direct Upload point (in my case this is /upload)

  4. Create a method to send the picture

    sendPicture(filepath) {
        // Rails server direct upload point
        var url = "/upload";
    
        // Get the name of the image
        var name = filepath.substr(filepath.lastIndexOf("/") + 1);
    
        // upload configuration
        var bghttp = require("nativescript-background-http");
        var session = bghttp.session("image-upload");
        var request = {
            url: url,
            method: "POST",
            headers: {
                "file-name": name,
                "Content-Type": "application/octet-stream"
            },
            description: "Uploading " + name
        };
    
        var params = [
            {
                name: "file",
                filename: filepath,
                mimeType: "image/jpeg"
            }
        ];
    
        var task = session.multipartUpload(params, request);
    
        task.on("error", this.errorHandler);
        task.on("responded", this.respondedHandler, this);
        task.on("complete", this.completeHandler);
    }

    NOTE: you have to pass 'this' as the third parameter of responded otherwise you cannot access your data model which in my case was this._dataItem within the function.

    NOTE: Shrine requires the param['name'] to be set to "file"

  5. Create a model which to save the image hash returned from shrine

    export class DataItem {
        constructor(public id: string,
                    public task: string,
                    public image: string,
                   ) { }
    }
  6. On response from Shrine store the stringified JSON

    errorHandler(e) {
        alert("received " + e.responseCode + " code.");
        var serverResponse = e.response;
    }
    
    respondedHandler(e) {
        alert("received " + e.responseCode + " code. Server sent: " + e.data);
        this._dataItem.image = JSON.stringify(e.data);
    }
    
    completeHandler(e) {
        alert("received")
    }
  7. Then you can post the rest of the form like so:

    create(item: DataItem) {
        let params = new URLSearchParams();
    
        return this.http.post(this.url,
                              {todo: item},
                              {  }
                             ).pipe(
                                 catchError(this.handleErrors)
                             );
    
    }

    NOTE: This sends other form elements such as 'task' and the important response which Shrine gave us.