1

I'm trying to send some files and data back from a NodeJS server to a client that works in JQuery. I use res.sendfile() to return files from the NodeJS server, but that downloads the file on the client computer. I only want to send the file back to the JQuery code (Written in Typescript) and enable it being manipulated or rendered by the JQuery code. How can I do that?

I am also trying to send JSON data back to the client but the JSON data gets rendered on the client side, instead of being handled by the JQuery code.

Here's the client side code that receives a JSON message after file upload

function sendFile() {

    $(new ID().setAsRoot().selectId()).append(
        "<form id=\"fileUploadForm\" accept-charset=\"utf-8\" method=\"post\" action=\"/upload\" enctype=\"multipart/form-data\"><input id = \"filename\" type=\"file\" name=\"userfile\" multiple=\"multiple\" /><button type=\"submit\"> Upload </button></form>");

    var $form = $("#fileUploadForm");
    alert("Started");
    $form.submit(function (e) {
        // perform client side validations if any

        this.ajaxSubmit({
            error: function () {
                alert("Error");
            },

            success: function (response) {
                var x = response.message;
                alert("Success  : " + x);
            }
        });

        // Important: stop event propagation
        return false;
    });
}

Here's the server side code for sending the response:

respond: function respond(req, res, next) {
        console.log("Responding");
        var response = {
            result: 'success',
            upload: req.uploadLink,
            message: 'File uploaded!'
        };
        res.status(200).json(response);
        console.log("Response complete");
    },

Here's the JSON getting rendered on the screen:

{
  "result": "success",
  "upload": "\\data\\tempFile4",
  "message": "File uploaded!"
}
mcuadros
  • 3,854
  • 2
  • 33
  • 43
EternallyCurious
  • 2,245
  • 6
  • 41
  • 73
  • it is possible by using byte streams. Check this answer: http://stackoverflow.com/questions/2558606/stream-data-with-node-js – Bart Dec 07 '13 at 09:37

1 Answers1

3

to send JSON data or any data you can use, res.send({})

app.get('/filepath.json', function(req, res){
  var response = {
        result: 'success',
        upload: req.uploadLink,
        message: 'File uploaded!'
    };
  res.send(response)
});
makenova
  • 3,149
  • 3
  • 14
  • 20