So I am doing an ajax(jquery) post that uploads quite a big amount of json data. When posting a large data, the data is generally broken into chunks. So we have to listen for post data requests and construct a full buffer of the upload data. Something like this:
req.on('data', function(chunk) {
console.log("upload on data "+ chunk.length);
chunks.push(chunk);
total+= chunk.length;
});
req.on('error', function(e) {
console.log('Got Error ' + e.message);
});
req.on('end', function() {
var buf = new Buffer(total)
cur = 0;
for (var i = 0, l = chunks.length; i < l; i++) {
chunks[i].copy(buf, cur, 0);
cur += chunks[i].length;
}
var level = 1;
var path = "level"+level+".json";
writeToFile(buf,path);
res.send("Update successfull as level "+level);
});
This seems to be working if I am uploading a file with form:
function display_form(req, res) {
res.sendHeader(200, {"Content-Type": "text/html"});
res.write(
'<form action="/upload" method="post" enctype="multipart/form-data">'+
'<input type="file" name="upload-file">'+
'<input type="submit" value="Upload">'+
'</form>'
);
res.close();
}
But I need to upload json data (which is dynamic). I am doing this in this way:
$.ajax({
type: "POST",
url: "/upload",
data: {"data": JSON.stringify(gamePack)},
success: cb,
});
Then there seems to be no callback to req ‘data’ or ‘end’. So how are uploading files different from posting data?
This seems to have solved my problem: