javascript - 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 字符串?谢谢你的任何想法。
解决方案
推荐阅读
- python - 这段代码不起作用,但我真的觉得它应该是
- api - 颤振发布请求
- python - 如何为.loc pandas动态添加条件
- regex - Python Regex 用于句子中的介词
- c - 是否有可能告诉 gcc 编译器忽略函数属性?还是加快编译时间?
- azure - 局域网中所有计算机的根证书,用于 Azure 的点到站点 VPN 连接
- authentication - 如何将用户和密码身份验证发送到 OSB 12c 中的旧版?
- javascript - 如何在 React 中实现路由?
- shopify - 如何根据特定条件重复部分迭代?
- azure - 如何将 SOAP 请求的 DateTime 传递给 azure web api?