在我的Nativescript应用程序中,我想使用相机模块捕获图像,然后通过http调用将字节直接发送到服务器。
这是我的代码(为简洁起见不完整):
var cameraModule = require("camera");
var http = require("http");
...
cameraModule.takePicture().then(function (img) {
// how to extract the actual bytes from img???
http.request({
url: some_url,
method: "POST",
headers: { "Content-Type": "application/octet-stream" },
content: ???
});
});
有办法吗?
我正在查看nativescript-background-http,它似乎完全符合我的要求,但该示例显示了仅从路径加载的文件。我没有运气使这个在iOS上运行。
非常感谢任何帮助。
谢谢。
答案 0 :(得分:5)
一些事情;
所以这里基本上是我会怎么做(在android下测试)。
var cameraModule = require('camera');
var some_url="http://somesite";
// img is a image source
cameraModule.takePicture().then(function (img) {
// You can use "jpeg" or "png". Apparently "png" doesn't work in some
// cases on iOS.
var imageData = img.toBase64String("jpeg");
http.request({
url: some_url,
method: "POST",
headers: { "Content-Type": "application/base64" },
content: imageData
}).then(function() {
console.log("Woo Hoo, we sent our image up to the server!");
}).catch(function(e) {
console.log("Uh oh, something went wrong", e);
});
});
答案 1 :(得分:2)
有几种方法可以做到这一点。如果您的后端可以使用base64字符串,则可以使用image-source类并操作数据。我正在打电话或者我会模拟样品。这实际上取决于您对服务器的期望,但使用image-source和ui / image组件的NativeScript可以实现大多数选项。
http://docs.nativescript.org/api-reference/classes/_image_source_.imagesource.html#tobase64string
从内存开始,但是当你回到(IMG)时尝试这个。
var data = img.tobase64string();
应该为您提供图像的基本64字符串。
刚从另一个问题https://stackoverflow.com/a/37815237/1893557找到了这个很棒的样本 这将在本地保存文件后使用background-http插件发送文件。