Nativescript将摄像头捕获发送到服务器

时间:2016-06-20 22:38:24

标签: nativescript

在我的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上运行。

非常感谢任何帮助。

谢谢。

2 个答案:

答案 0 :(得分:5)

一些事情;

  1. " IMG"实际上是一个图像源。
  2. 此时内置的HTTP模块不支持直接二进制传输,因此我们需要将其转换为可通过线路发送的内容。因此base64是一个可以支持二进制的文本表示,它是一种常见的编码/解码方法。
  3. 由于我们已将它作为图像源使用,我们只需使用cool toBase64String功能,它可以为我们提供Base 64数据。
  4. 所以这里基本上是我会怎么做(在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插件发送文件。