Thursday, 18 May 2017

Creating a JSON file and POSTting to server

I am trying to send JSON created in JavaScript on client side to server using code i got.

Here is my server side code:

var http = require('http'),
path = require('path'),
fs = require('fs');

var Busboy = require('busboy');
var express = require('express');
var app = express();
app.set('view engine', 'hjs');
var dir = './Files';
if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
}

app.get('/', function (req, res) {
res.render('index', {})
})
app.post('/', function (req, res) {
        var busboy = new Busboy({ headers: req.headers });
        busboy.on('file', function (fieldname, file, filename,encoding, mimetype) {

            var saveTo = path.join(dir, path.basename(filename));
            console.log(path.basename(filename));
            file.pipe(fs.createWriteStream(saveTo));


        });
        busboy.on('finish', function () {
            console.log('Done parsing form!');
            res.writeHead(303, { Connection: 'close', Location: '/' 
        });
            res.end();
        });
        req.pipe(busboy);
})
app.listen(8000, function () {
    console.log('Example app listening on port 8000!')
})

Here is client side:

<html>
<head>
</head>
<body>
    <form method="POST" enctype="multipart/form-data">
    <input type="file" name="filefield" ><br />
    <input type="submit">
    </form>
</body>
</html>

I don't want to the part for choosing the file as i want to submit file created in JavaScript.

I found this part o code which looks really useful but i don't how to pass values of it to input form with name of the file so it will get sent it as this file.

var obj = {a: 123, b: "4 5 6"}; var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj)); var file = new Blob([data], {type: type});

I wish to save file as certain file name as i would like to have some validation by file name and properties of the json but currently i can't even pass this JSON as a file to server only by using JavaScript it itself.



via AESTHETICS

No comments:

Post a Comment