Nativescript - How to POST Image with http.request

心不动则不痛 提交于 2019-12-06 06:53:17

I recommend using of nativescript-background-http plugin for uploading files.

tns plugin add nativescript-background-http

Here is your code modifed to work with the installed plugin:

"use strict";
var Observable = require("data/observable").Observable;
var cameraModule = require("camera");
var fs = require("file-system");

var bghttpModule = require("nativescript-background-http");
var session = bghttpModule.session("image-upload");

var viewModel = new Observable();

function navigatingTo(args) {
    var page = args.object;
    page.bindingContext = viewModel;
}
exports.navigatingTo = navigatingTo;

function onTap() {
    cameraModule.takePicture({
        width: 300,
        height: 300,
        keepAspectRatio: true
    }).then(function (imageSource) {
        console.log("Image taken!");
        var folder = fs.knownFolders.documents();
        var path = fs.path.join(folder.path, "Test.png");
        var saved = imageSource.saveToFile(path, "png");
        var request = {
            url: "http://httpbin.org/post",
            method: "POST",
            headers: {
                "Content-Type": "application/octet-stream",
                "File-Name": "Test.png"
            },
            description: "{ 'uploading': " + "Test.png" + " }"
        };

        var task = session.uploadFile(path, request);
        task.on("progress", logEvent);
        task.on("error", logEvent);
        task.on("complete", logEvent);

        function logEvent(e) {
            console.log("----------------");
            console.log('Status: ' + e.eventName);
            // console.log(e.object);
            if (e.totalBytes !== undefined) {
                console.log('current bytes transfered: ' + e.currentBytes);
                console.log('Total bytes to transfer: ' + e.totalBytes);
            }
        }
    });
}
exports.onTap = onTap;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!