Ajax phonegap image post - ajax

Below is the piece of code i have used:
JSON.stringify({
request:
{
"Ticket": "String content",
"Picture": {
"Name": "blabla",
"ImgData": "blabla",
},
}
});
i have picture , i captured with phonegap and i wanna post it with json. is it possible ?

Upload/Post image using phonegap
function uploadPhoto(imageURI) {
var imagefile = imageURI;
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert($.parseJSON(r.response))
}
function fail(error) {
console.log("Response = " + error.code);
}

if you want to upload it inside json data you'll need to send the image encoded in base64, for that use the destinationType: Camera.DestinationType.DATA_URL when you take the picture

Related

nativescript-background-http issue

I tried implementing image upload page for my app, but unfortunately the request is not reaching the server. I double checked this using tcpdump on the server side. The code doesnt seem to process beyond session.uploadFile in sendImages function
Please let me know if there is any issue with the code
var imageSource = require("image-source");
var frameModule = require("ui/frame");
var Observable = require("data/observable").Observable;
var fromObject = require("data/observable").fromObject;
var ObservableArray = require("data/observable-array").ObservableArray;
var platformModule = require("platform");
var permissions = require("nativescript-permissions");
var imagepickerModule = require("nativescript-imagepicker");
var bghttpModule = require("nativescript-background-http");
var session = bghttpModule.session("image-upload");
var fs = require("file-system");
var page;
var imageName;
var counter = 0;
function pageLoaded(args) {
page = args.object;
}
function onSelectSingleTap(args) {
var context = imagepickerModule.create({
mode: "single"
});
if (platformModule.device.os === "Android" && platformModule.device.sdkVersion >= 23) {
permissions.requestPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, "I need these permissions to read from storage")
.then(function () {
console.log("Permissions granted!");
startSelection(context);
})
.catch(function () {
console.log("Uh oh, no permissions - plan B time!");
});
} else {
startSelection(context);
}
}
function sendImages(uri, fileUri) {
imageName = extractImageName(fileUri);
var request = {
url: "http://maskingIpForPost:8081/mobilepic/ctk/uploadpic",
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"file-Name": imageName,
"uid": 30
},
description: "{ 'uploading': " + imageName + " }"
};
var task = session.uploadFile(fileUri, request);
task.on("progress", progress);
task.on("error", error);
task.on("complete", complete);
task.on("responded", responded);
function responded(e) {
console.log("eventName: " + e.eventName);
console.log("data: " + e.data);
}
function progress(e) {
console.log("currentBytes: " + e.currentBytes);
console.log("totalBytes: " + e.totalBytes);
console.log("eventName: " + e.eventName);
}
function error(e) {
console.log("eventName: " + e.eventName);
console.log("eventName: " + e.responseCode);
console.log("eventName: " + e.response);
}
function complete(e) {
console.log("eventName: " + e.eventName);
console.log("response: " + e.responseCode);
}
return task;
}
function startSelection(context) {
context
.authorize()
.then(function () {
return context.present();
})
.then(function (selection) {
selection.forEach(function (selected_item) {
var localPath = null;
if (platformModule.device.os === "Android") {
localPath = selected_item._android;
} else {
// selected_item.ios for iOS is PHAsset and not path - so we are creating own path
let folder = fs.knownFolders.documents();
let path = fs.path.join(folder.path, "Test" + counter + ".png");
//let saved = imagesource.saveToFile(path, "png");
localPath = path;
}
alert("final path " + localPath);
if (localPath) {
var task = sendImages("Image" + counter + ".png", localPath);
//mainViewModel.get("items").push(fromObject({ thumb: imagesource, uri: "Image" + counter + ".png", uploadTask: task }));
}
counter++;
});
}).catch(function (e) {
console.log(e.eventName);
});
}
function extractImageName(fileUri) {
var pattern = /[^/]*$/;
var imageName = fileUri.match(pattern);
return imageName;
}
exports.pageLoaded = pageLoaded;
exports.onSelectSingleTap = onSelectSingleTap;
On Further research found the following
net.gotev.uploadservice.UploadService is undefined in background-http.android.js. At this moment i am not sure what this means. Would appreciate if anyone has idea about this
You need to change the following line in your code.
var session = bghttpModule.session("image-upload");
It has to be file upload
var session = bghttpModule.session("file-upload");
Just tested your code by using Azure Blob Storage PUT url at my side and got the below response.
ActivityManager: START u0 {act=android.intent.action.OPEN_DOCUMENT typ=image/* cmp=com.android.documentsui/.DocumentsActivity (has extras)} from pid 2835
JS: currentBytes: 4096
JS: totalBytes: 25220
JS: eventName: progress
JS: currentBytes: 25220
JS: totalBytes: 25220
JS: eventName: progress
JS: currentBytes: 25220
JS: totalBytes: 25220
JS: eventName: progress
JS: eventName: responded
JS: data:
JS: eventName: complete
JS: response: 201
thanks for the quick response, i tried running it on a emulator and i faced the above mentioned issue, i tried the same by connecting a device and it worked just fine.

SAPUI5 file upload download gets corrupted

Can someone help me.
I've implemented a file upload / download in UI5 that seems to work but when I download the file it gets corrupted and I can't open it.
For now I'm only testing with image files:
new sap.ui.unified.FileUploader({
buttonOnly: true,
buttonText: "Upload files",
icon: "sap-icon://upload",
change: function(oEvent) {
var oFileUploader = oEvent.getSource();
oItem = oFileUploader.getParent().getParent().getParent();
var sPath = oItem.getBindingContext().getPath();
var files = oEvent.getParameter("files");
var file = files[0];
if (file) {
var oNewFile = {
ID: that.count++,
SurveyAnswerID: oSA.ID,
FileName: oEvent.getParameter("newValue"),
FileBinary: null,
MimeType: "image/jpeg",
Mode: "POST"
};
var reader = new FileReader();
reader.onload = function(evt) {
var binaryString = evt.target.result;
oNewFile.FileBinary = binaryString;
};
reader.readAsBinaryString(file);
} else {
oNewFile.FileBinary = "";
oNewFile.FileName = "";
MessageToast.show("Something went wrong with the file upload.\n Please try again");
}
that._pushItemToFileUploadModel(oNewFile.ID, oNewFile);
that._getFileUploadModel().refresh();
}
})
Download code:
selectionChange: function(oEvent) {
var item = oEvent.getSource().getSelectedItem();
var model = that._getFileUploadModel();
if (item) {
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([item.getDocumentId()], {
type: item.getMimeType()
}));
a.download = item.getFileName();
// Append anchor to body.
document.body.appendChild(a);
a.click();
// Remove anchor from body
document.body.removeChild(a);
}
try {
oEvent.getSource()._oList.removeSelections();
} catch (e) {
//DO nothing
}
},
What an I doing wrong here?
I solved my issue converting the file this way:
var u8_2 = new Uint8Array(atob(data).split("").map(function(c) {
return c.charCodeAt(0);
}));
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([u8_2], {
type: item.getMimeType()
}));

Nativescript - How to POST Image with http.request

Help, I need call the http.request for send Image captured in camera api in my NativeScript App.
I capture the photo in camera api for nativescript and need send to api in upload process.
Follow the code about this process:
var frameModule = require("ui/frame");
var viewModule = require("ui/core/view");
var Observable = require("data/observable").Observable;
var config = require("../../shared/config");
var cameraModule = require("camera");
var imageModule = require("ui/image");
var http = require("http");
exports.loaded = function(args) {
var page = args.object;
viewModel = new Observable({
coleta: config.id_coleta
});
page.bindingContext = viewModel;
};
exports.voltar = function() {
var topmost = frameModule.topmost();
topmost.navigate("views/ocorrencia/menuocorrencia");
};
function tapFoto() {
cameraModule.takePicture({
width: 300,
height: 300,
keepAspectRatio: true
}).then(function(picture) {
var image = new imageModule.Image();
image.imageSource = picture;
var item = {
itemImage: picture
};
var urlfoto = "http://192.1.1.1:8090/sendphoto/upload";
alert("URL: " + urlfoto);
http.request({
url: urlfoto,
method: "POST",
headers: {
"Content-Type": "multipart/form-data"
},
content: ({uploadFile: image.imageSource, entrega: config.id_coleta})
}).then(function (response) {
var statusCode = response.statusCode;
alert("Codigo Retorno: " + statusCode);
alert("Foto registrada com sucesso.");
}, function (e){
alert("Erro: " + e);
});
});
}
exports.tapFoto = tapFoto;
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;

image upload to a .NET server

This is the code I'm using. How do I specify the .NET server address which should receive the image?
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {
var oOutput = document.querySelector("div"),
oData = new FormData(form);
oData.append("CustomField", "extra data");
var oReq = new XMLHttpRequest();
oReq.open("POST", "abcd", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
}
else
{
oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
Create a generic handler. In ProcessRequest event, put this base code
public void ProcessRequest(HttpContext context)
{
HttpPostedFile doc = context.Request.Files[0];
//Your code....
doc.SaveAs("YOUR_PATH" + "/" + doc.FileName);
}
The ajax post should go to this resource...

Node.JS convert Variable-length binary data to jpeg or png?

I was wondering how to convert Variable-length binary data(255216255224016747073700110010100255) to a jpeg or png to the web browser?
Example Code:
var Connection = require('tedious').Connection;
var config = {
"userName": "user#server.database.windows.net",
"password": "pswd",
"server": "server.database.windows.net",
"options": {
"database": "db",
"encrypt": true,
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
console.log("Connected");
}
);
var Request = require('tedious').Request;
var result,
resG;
function sendResponse() {
var vals;
// Convert to string then array
var resultA = result.toString().split(',');
// Now I can loop through the data returned
resultA.forEach(function(val, index, ar) {
if(vals == null) {
vals = val;
} else {
vals += val;
}
});
resG.writeHead(200, {'Content-Type': 'text/html', 'Content-Length': vals.length});
//console.log(vals);
//resG.end("<img src=\"data:image/jpg;base64," + vals + "\" />");
// Output data returned from db as string
resG.end("" + vals);
}
function executeStatement() {
request = new Request("SELECT Photos FROM dbo.tbl WHERE FarmerFirstName='someName' AND FarmerLastName='someLastName'", function(err, rowCount) {
if (err) {
console.log(err);
} else {
console.log(rowCount + ' rows');
}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
result = column.value;
});
});
request.on('doneInProc', function(rowCount, more) {
// Got everything needed from db move on to sending a response
sendResponse();
});
connection.execSql(request);
}
var http = require('http'),
director = require('director');
var router = new director.http.Router({
"/": {
get: executeStatement
}
});
var server = http.createServer(function (req, res) {
// set global res var
resG = res;
router.dispatch(req, res, function (err) {
if (err) {
res.writeHead(404);
res.end();
}
});
});
server.listen(80);
I'm using tedious for my db connector and director as my router.
The result is already an array of bytes for the Image. You do not need to do any fancy transformations on it. This should work.
function sendResponse() {
resG.writeHead(200, {'Content-Type': 'image/jpeg', 'Content-Length': result.length});
resG.end(new Buffer(result));
}
or if you want to serve it as part of an HTML page, this:
function sendResponse() {
resG.writeHead(200, {'Content-Type': 'text/html'});
var vals = (new Buffer(result)).toString('base64')
resG.end("<html><body>" +
"<img src=\"data:image/jpg;base64," + vals + "\" />" +
"</body></html>");
}

Resources