首页 > 解决方案 > Nativescript - 使用 http 模块上传图片

问题描述

我正在使用“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 字符串?谢谢你的任何想法。

在附图下方,base64 字符串在质量在此处输入图像描述设置为 1 的情况下有多长。

标签: javascriptnativescript

解决方案


推荐阅读