send params to node server using cordova - node.js

I'm trying to upload file and send params in the same request it's possible with filetransfer but i have a problem in the server side the req.body is always empty i'm using formidable module
this is the client side
upload = function (imageURI) {
var ft = new FileTransfer(),
options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = 'filename.jpg'; // We will use the name auto-generated by Node at the server side.
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
alert(imageURI);
ft.upload(imageURI, serverURL + "/upload",
function (e) {
getFeed();
},
function (e) {
alert("Upload failed");
}, options);
},
this is the server side
var form = new formidable.IncomingForm();
form.parse(req, function(error, fields, files) {
console.log(req.body.value1);
console.log("Traitement terminé");

i found the problem i had to replace
console.log(req.body.value1);
by
console.log(fields.value1);

Related

How to send file data in post request in node using request module?

Requirement:
I need to make an api call with the file uploaded by the user.My server is node and I use request module for making api calls.
Below is the code when user uploads a file and submits it.
if(queryData.sub == "upload"){
var input = {};
var formidable = require('formidable');
var form = new formidable.IncomingForm();
form.parse(request, function (err, fields, files) {
var fs = require('fs');
fs.readFile(files.filetoupload.path, function(err, data) {
input.x_file_content = data;
client.API.ATTACHMENTS.uploadFile(input).then(function(resp){
var str = settings.layoutParsing(resp);
response.write(str);
response.end();
})
});
});
}
}
In upload file function i use FormData to set the file and send it while making api call .Below is the code:
if (request.x_file_content) {
var FormData = require('form-data');
var formData = new FormData();
formData.append('file', request.x_file_content);//No I18N
req_body = formData;
}
...
var httpclient = require('request');
httpclient({
uri : baseUrl,
method : request.type,
headers : api_headers,
responseType : responseType,
body : req_body
},function(error,response,body){
Problem:
but the file was not successfully sent and multipart content required error is thrown by the api server.
Can anyone point out what mistake Im doing.
Thanks !
found out the mistake,
setting header and replaced
fs.readFile(files.filetoupload.path, function(err, data) {
with readStream = fs.createReadStream("path to file");
rectified code :
input.x_file_content = readStream;
..
var FormData = require('form-data');
form_Data = new FormData();
form_Data.append('file', request.x_file_content);//No I18N
req_body = form_Data;
api_headers = form_Data.getHeaders();

Implement Redis in Node.js Bot Service

Bot Info
App ID: 776ba3b4-38e5-4582-809d-7c8d773cfe9b
SDK Platform: Node.js
SDK Version:
Active Channels: Direct Line
Deployment Environment: Auzure Bot Service
Issue Description
I Need Help implementing Redis to save Bot State. I'm working in a project that is really a requirement that we reduce as much latency as possibe. Right know we are using DocumentDB but since Redis works with memory this could be faster.
I've followed the tutorial using mongo DB, Microsoft Bot framework MongoDB as middle layer to store conversational states, data and context and I'm editing the file /lib/IStorageClient.js to connect, save and retrieve from redis.
Code Example
This is my implementation of the /lib/IStorageClient.js, instead of using MongoDB connection I've put Redis connection
"use strict";
var Consts = require('./Consts');
var redis = require('redis');
var IStorageClient = (function () {
function IStorageClient(options) {
this.options = options;
}
IStorageClient.prototype.initialize = function (callback) {
var _this = this;
var host = "MyRedis.redis.cache.windows.net";
var auth = "KEY";
var client = redis.createClient(6380,host , {auth_pass: auth, tls:
{servername: host}});
this.client = client;
callback(null);
};
IStorageClient.prototype.insertOrReplace = function (partitionKey, rowKey,
entity, isCompressed, callback) {
console.log("=========Insert IStorageClient===========")
var docDbEntity = { id: partitionKey + ',' + rowKey, data: entity,
isCompressed: isCompressed };
var host = "MyRedis.redis.cache.windows.net";
var auth = "KEY";
var client = redis.createClient(6380,host , {auth_pass: auth, tls:
{servername: host}});
client.set(partitionKey + ',' + rowKey, JSON.stringify(docDbEntity),
function(err, reply) {
console.log("=========SET===========");
console.log("ID: ",partitionKey + ',' + rowKey);
console.log("Result: ",docDbEntity);
});
};
IStorageClient.prototype.retrieve = function (partitionKey, rowKey,
callback) {
console.log("=========Retrieve IStorageClient===========")
var id = partitionKey + ',' + rowKey;
var host = "MyRedis.redis.cache.windows.net";
var auth = "KEY";
var client = redis.createClient(6380,host , {auth_pass: auth, tls:
{servername: host}});
//id
client.get(id, function(error, result){
console.log("=========Get===========");
console.log("Search: ",id);
console.log("Result: ",result);
if (error) {
console.log("Error:",error)
callback(error, null, null);
}
else if (result == null) {
callback(null, null, null);
}
else if (result.length == 0) {
callback(null, null, null);
}
else {
var finaldoc = JSON.parse(result);
callback(null, finaldoc, null);
}
});
};
IStorageClient.getError = function (error) {
if (!error)
return null;
return new Error('Error Code: ' + error.code + ' Error Body: ' +
error.body);
};
return IStorageClient;
}());
exports.IStorageClient = IStorageClient;
Reproduction Steps
Download Microsoft Bot framework MongoDB as middle layer to store conversational states, data and context
Replace /lib/IStorageClient.js with my implementation
Set a Redis account and key in the /lib/IStorageClient.js
Run in the bot emulator
Actual Results
I could see the json saving to Redis, also I could print the retrieve result in the console, but the thing is that the answer is not being received in the bot emulator.
You are looking for botbuilder-redis-storage middleware, available here:
GitHub - https://github.com/suttna/botbuilder-redis-storage
NPM - https://www.npmjs.com/package/botbuilder-redis-storage
Usage example:
var redis = require('redis')
var RedisStorage = require('botbuilder-redis-storage')
var builder = require('botbuilder')
// Initialize redis client
var redisClient = redis.createClient(process.env.REDIS_URL, { prefix: 'bot-storage:' });
// Create new storage with redis client
var storage = new RedisStorage(redisClient)
var connector = new builder.ChatConnector()
var bot = new builder.UniversalBot(connector)
// Configure bot to use the RedisStorage
bot.set('storage', storage)

On which format send file to save it on gridfs?

Hy every one,
Please , i 'm study on a project using nodeJS, and i would like to know , in which format my node client must send the file to the server ( is it in base64 format or else ?).
my client is :
//client.js
$('#file').on('change', function(e){
encode64(this);
});
function encode64(input) {
if (input.files){
chap.emit('test', { "test" : input.files[0] });
var FR= new FileReader();
FR.readAsDataURL(input.files[0]);
FR.onload = function(e) {
chap.emit('test', { "test" : e.target.result } );
}
}
}
My server side is :
socket.on('test', function(e){
var gs = new gridStore(db, e.test,"w");
gs.writeFile(new Buffer(e.test,"base64"), function(err,calb){
if (!err)
console.log('bien passe');
else
console.log('erreur');
});
});
But this doesn't work , i get this error :
TypeError: Bad argument
at Object.fs.fstat (fs.js:667:11)
Any one could help me ?
Normally this is how you store into gridFs . I have used it to store files. hope it works.
fs = require('fs'),
var gfs = require('gridfs-stream');
var form = new multiparty.Form();
form.parse(req, function (err, fields, files) {
var file = files.file[0];
var filename = file.originalFilename; //filename
var contentType = file.headers['content-type'];
console.log(files)
var tmpPath = file.path ;// temporary path
var writestream = gfs.createWriteStream({filename: fileName});
// open a stream to the temporary file created by Express...
fs.createReadStream(tmpPath)
// and pipe it to gfs
.pipe(writestream);
writestream.on('close', function (file) {
// do something with `file`
res.send(value);
});
})

image upload with "post" in nodejs with request module

How do we upload an image received form the mobile app to another server using the request module in nodejs?
I have tried using the multipart module to extract the file and send it in formData attribute with the request module (post method). This doesn't seem to work.
Please Use following code, it has been tested in express. you can modify it according to your requirement
var path = require('path');
var util = require('util');
if (req.files.profile_image !== undefined) {
var file = req.files.profile_image;
var tmp_path = file.path;
var fileName = file.name;
var milliseconds = new Date().getTime();
var file_ext = fileName.substr((Math.max(0, fileName.lastIndexOf(".")) || Infinity) + 1);
var newFileName = requestedUser + '_' + milliseconds + '.' + file_ext;
var pathToFile = require('path').dirname(require.main.filename);
var mainPath = path.dirname(pathToFile)
var target_path = path.join(mainPath, 'public/uploads/users', newFileName);
var readStream = fs.createReadStream(tmp_path)
var writeStream = fs.createWriteStream(target_path);
util.pump(readStream, writeStream, function(err) {
if (err) {
//handle error
} else {
//successfully uploaded
}
});
} else {
//file not recieved
}
Thanks

Uncompress gzipped http request body to json in Node.js

I have a windows 8 application connecting to a web service written in Node.js. On the windows 8 side I compressed my request body to gzip. But on the Node.js side I found that my req.body type was Object.
I cannot use zlib to uncomporess the body since it's not a stream.
I can use zlib to uncomporess the req, but I don't know how to retrieve the req.body content from the unzipped stream and parse the body in JSON format.
BTW, I reviewed my request through Fiddler and it told me the request body was gzipped, and I can see my raw body through Fiddler after unzipped so the request should be correct.
Updated
Below is my Node.js app
(function () {
var express = require("express");
var zlib = require("zlib");
var app = express();
var port = 12345;
app.configure(function () {
app.use(express.compress());
app.use(express.bodyParser());
});
app.post("/test", function (req, res) {
var request = req.body;
req.pipe(zlib.createGunzip());
var response = {
status: 0,
value: "OK"
};
res.send(200, response);
});
console.log("started at port %d", port);
app.listen(port);
})();
And below is my windows store app code (partial)
private async void button1_Click_1(object sender, RoutedEventArgs e)
{
var message = new
{
Name = "Shaun",
Value = "12345678901234567890123456789012345678901234567890"
};
var json = await JsonConvert.SerializeObjectAsync(message, Formatting.Indented);
var bytes = Encoding.UTF8.GetBytes(json);
var client = new HttpClient();
client.BaseAddress = new Uri("http://192.168.56.1:12345/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.ExpectContinue = false;
var jsonContent = new JsonContent(message);
var gzipContent = new GZipContent3(jsonContent);
var res = await client.PostAsync("test", gzipContent);
var dialog = new Windows.UI.Popups.MessageDialog(":)", "完成");
await dialog.ShowAsync();
}
internal class GZipContent3 : ByteArrayContent
{
public GZipContent3(HttpContent content)
: base(LoadGZipBytes(content))
{
//base.Headers.ContentType = content.Headers.ContentType;
base.Headers.ContentType = new MediaTypeHeaderValue("x-application/x-gzip");
base.Headers.ContentEncoding.Add("gzip");
}
private static byte[] LoadGZipBytes(HttpContent content)
{
var source = content.ReadAsByteArrayAsync().Result;
byte[] buffer;
using (var outStream = new MemoryStream())
{
using (var gzip = new GZipStream(outStream, CompressionMode.Compress, true))
{
gzip.Write(source, 0, source.Length);
}
buffer = outStream.ToArray();
}
return buffer;
}
}
internal class JsonContent : StringContent
{
private const string defaultMediaType = "application/json";
public JsonContent(string json)
: base(json)
{
var mediaTypeHeaderValue = new MediaTypeHeaderValue(defaultMediaType);
mediaTypeHeaderValue.CharSet = Encoding.UTF8.WebName;
base.Headers.ContentType = mediaTypeHeaderValue;
}
public JsonContent(object content)
: this(GetJson(content))
{
}
private static string GetJson(object content)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
var json = JsonConvert.SerializeObject(content, Formatting.Indented);
return json;
}
}
http://www.senchalabs.org/connect/json.html. Basically you need to write your own middleware based on connect.json() that pipes through an uncompression stream like connect.compress() but the opposite direction: http://www.senchalabs.org/connect/compress.html
Also, make sure you're sending the correct Content-Encoding header in your request.
If you show me what you have so far I can help you further.
I was working on similar thing and finally landed on
function getGZipped(req, callback) {
var gunzip = zlib.createGunzip();
req.pipe(gunzip);
var buffer = [];
gunzip.on('data', function (data) {
// decompression chunk ready, add it to the buffer
buffer.push(data);
}).on('end', function () {
//response and decompression complete, join the buffer and return
callback(null, JSON.parse(buffer));
}).on('error', function (e) {
callback(e);
});
}

Resources