nativescript-background-http проблема

Я попытался реализовать страницу загрузки изображений для своего приложения, но, к сожалению, запрос не доходит до сервера. Я дважды проверил это с помощью tcpdump на стороне сервера. Код, похоже, не обрабатывается за пределами session.uploadFile в функции sendImages

Пожалуйста, дайте мне знать, если есть проблема с кодом

var imageSource = require("image-source");
var frameModule = require("ui/frame");
var Observable = require("data/observable").Observable;
var fromObject = require("data/observable").fromObject;
var ObservableArray = require("data/observable-array").ObservableArray;
var platformModule = require("platform");

var permissions = require("nativescript-permissions");
var imagepickerModule = require("nativescript-imagepicker");
var bghttpModule = require("nativescript-background-http");
var session = bghttpModule.session("image-upload");

var fs = require("file-system");


var page;
var imageName;
var counter = 0;

function pageLoaded(args) {
    page = args.object;
}


function onSelectSingleTap(args) {
    var context = imagepickerModule.create({
        mode: "single"
    });

    if (platformModule.device.os === "Android" && platformModule.device.sdkVersion >= 23) {
        permissions.requestPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, "I need these permissions to read from storage")
            .then(function () {
                console.log("Permissions granted!");
                startSelection(context);
            })
            .catch(function () {
                console.log("Uh oh, no permissions - plan B time!");
            });
    } else {
        startSelection(context);
    }
}

function sendImages(uri, fileUri) {

    imageName = extractImageName(fileUri);
    var request = {
        url: "http://maskingIpForPost:8081/mobilepic/ctk/uploadpic",
        method: "POST",
        headers: {
            "Content-Type": "application/octet-stream",
            "file-Name": imageName,
            "uid": 30
        },
        description: "{ 'uploading': " + imageName + " }"
    };

    var task = session.uploadFile(fileUri, request);

    task.on("progress", progress);
    task.on("error", error);
    task.on("complete", complete);
    task.on("responded", responded);
    function responded(e) {
        console.log("eventName: " + e.eventName);
        console.log("data: " + e.data);
    }
    function progress(e) {
        console.log("currentBytes: " + e.currentBytes);
        console.log("totalBytes: " + e.totalBytes);
        console.log("eventName: " + e.eventName);
    }
    function error(e) {
        console.log("eventName: " + e.eventName);
        console.log("eventName: " + e.responseCode);
        console.log("eventName: " + e.response);
    }

    function complete(e) {
        console.log("eventName: " + e.eventName);
        console.log("response: " + e.responseCode);
   }

    return task;
}

function startSelection(context) {

    context
        .authorize()
        .then(function () {

            return context.present();
        })
        .then(function (selection) {
            selection.forEach(function (selected_item) {
                    var localPath = null;

                    if (platformModule.device.os === "Android") {
                        localPath = selected_item._android;
                    } else {
                        // selected_item.ios for iOS is PHAsset and not path - so we are creating own path
                        let folder = fs.knownFolders.documents();
                        let path = fs.path.join(folder.path, "Test" + counter + ".png");
                        //let saved = imagesource.saveToFile(path, "png");

                        localPath = path;
                    }
alert("final path  " + localPath);
                    if (localPath) {
                        var task = sendImages("Image" + counter + ".png", localPath);
                        //mainViewModel.get("items").push(fromObject({ thumb: imagesource, uri: "Image" + counter + ".png", uploadTask: task }));
                    }
                    counter++;
            });
        }).catch(function (e) {
            console.log(e.eventName);
        });
}

function extractImageName(fileUri) {
    var pattern = /[^/]*$/;
    var imageName = fileUri.match(pattern);

    return imageName;
}


exports.pageLoaded = pageLoaded;
exports.onSelectSingleTap = onSelectSingleTap;

При дальнейших исследованиях были обнаружены следующие

net.gotev.uploadservice.UploadService не определен в background-http.android.js. На данный момент я не совсем понимаю, что это значит. Был бы признателен, если бы кто-нибудь знал об этом


person siva    schedule 11.10.2018    source источник
comment
вы можете запустить в режиме отладки и проверить в chrome devtools   -  person Narendra    schedule 11.10.2018
comment
Обычно это означает, что сторонняя библиотека (зависимость Java) установлена ​​неправильно. Заставить nativescript загружать зависимости через Gradle. Самое простое решение - rm -rf platforms и tns run android.   -  person Florian Thuin    schedule 11.10.2018
comment
Вы используете эмулятор или устройство для проверки? Если да, то какая версия!   -  person Baskar Rao    schedule 11.10.2018
comment
Вы столкнулись с проблемой на обеих платформах?   -  person Manoj    schedule 11.10.2018


Ответы (2)


Вам нужно изменить следующую строку в вашем коде.

var session = bghttpModule.session("image-upload");

Это должна быть загрузка файла

var session = bghttpModule.session("file-upload");

Просто протестируйте свой код, используя URL-адрес PUT хранилища BLOB-объектов Azure на моей стороне, и получил ответ ниже.

ActivityManager: START u0 {act=android.intent.action.OPEN_DOCUMENT typ=image/* cmp=com.android.documentsui/.DocumentsActivity (has extras)} from pid 2835

JS: currentBytes: 4096
JS: totalBytes: 25220
JS: eventName: progress
JS: currentBytes: 25220
JS: totalBytes: 25220
JS: eventName: progress
JS: currentBytes: 25220
JS: totalBytes: 25220
JS: eventName: progress
JS: eventName: responded
JS: data: 
JS: eventName: complete
JS: response: 201
person Baskar Rao    schedule 11.10.2018

спасибо за быстрый ответ, я попытался запустить его на эмуляторе, и я столкнулся с вышеупомянутой проблемой, я попробовал то же самое, подключив устройство, и он работал нормально.

person siva    schedule 11.10.2018