Nativescript-使用http模块上传图像

时间:2019-01-12 10:26:03

标签: javascript nativescript

我正在使用“ nativescript-imagepicker”插件从设备库中获取图像。 为此,我将调用这两个模块:

var imagepicker = require("nativescript-imagepicker");
var imageSourceModule = require("tns-core-modules/image-source");

现在我有一些显示画廊的功能,并且我可以选择一张图像,然后将其转换为base64字符串并分配为全局变量以供以后使用:

model.gallery = function () {
    var img;
    var context = imagepicker.create({mode: "single"});
    context.authorize()
        .then(function () {
            return context.present();
        })
        .then(function (selection) {
            selection.forEach(function (selected) {
                img = selected;
                model.set('avatar', img);
            });
            var source = new imageSourceModule.ImageSource();
            source.fromAsset(img)
                .then(function (imageSource) {
                    var convertedAvatar = imageSource.toBase64String("jpeg",1);
                    global.convertedAvatar = convertedAvatar;
                });
        }).catch(function (e) {
        alert ('Error, please try  again');
    });
};

一切似乎都可以正常工作,但请查看图像质量(1)。 我尝试过将质量设置为90,但似乎该字符串太长,以至于该http调用导致应用崩溃:

model.test = function() {
    var base64 = global.convertedAvatar;
    var content = 'type=profile&file='+base64+'&extension=jpeg';
    http.request({
        url: global.host + 'profile/upload',
        method: 'POST',
        headers: {"Content-Type": global.cType},
        content: content,
    }).then(function (response) {
        global.loaderHide();
        result = response.content.toJSON();
        if (response.statusCode == 200) {
            success('Success','Data saved.')
        } else {
            global.alerts('Error',result.message);
        }
    }).catch(function (error) {
        global.alerts('Error', error);
    });
};

我的问题是:由于存在问题,我认为我的方法是错误的。 Base64字符串很长。有办法做到这一点吗? 我是否可以调整图像大小,以便字符串可以更小? 还是这是API的问题(不接受很长的字符串)? 最后,也许我需要使用诸如背景http模块之类的另一种方法来上传图像,而不是base64字符串? 谢谢您的任何想法。

在所附图片下方,质量enter image description here设置为1的base64字符串有多长。

0 个答案:

没有答案
相关问题