Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sending text to the browser

Sending text to the browser

Problem

I have managed to get file uploading work in Node.js with Express, and in the code i'm checking whether it's an image or not that the user is trying to upload.

If the file was successfully uploaded I want to show a Message to the user, directly to the HTML page with the uploading form. The same should be if the file the user tried to upload wasn't an image, or something else happened during the upload.

The code below works (res.send...) but it opens up a new page containing only the message.

My question is: How can I change my code so that the message is sent directly to the HTML page instead? If it could be of any use, i'm using Jade.

Thanks in advance!

app.post('/file-upload', function(req, res, next) {
    var fileType = req.files.thumbnail.type;
    var divided = fileType.split("/");
    var theType = divided[0];

    if (theType === "image"){
        var tmp_path = req.files.thumbnail.path;

        var target_path = './public/images/' + req.files.thumbnail.name;

        fs.rename(tmp_path, target_path, function(err) {
            if (err) throw err;

            fs.unlink(tmp_path, function() {
                if (err) {
                    throw err;
                    res.send('Something happened while trying to upload, try again!');
                }
                res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
            });
        });
    }

    else {
        res.send('No image!');
    }

});
Problem courtesy of: holyredbeard

Solution

from what I understand you are trying to send a message to an already open browser window?

a few things you can do,

  1. Ajax it, send the post, and process the return info.
  2. Submit it as you are doing now, but set a flash message (look at http://github.com/visionmedia/express-messages) and either res.render the form page, or res.redirect to the form function
  3. now.js or a similar solution. This would let clientside use serverside functions and serverside code to run clientside functions. So what you would do would be on submit, pass the post values to a serverside function, which will process it and trigger a clientside function (display a message)

For my money option #2 is probably the safest bet, as clients without javascript enabled will be able to use it. As for usability #1 or #3 would give a more streamlined appearance to the end user.

Solution courtesy of: Last Rose Studios

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Sending text to the browser

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×