user2448953
user2448953

Reputation: 121

Upload Files with Websockets and Nodejs

I'm trying to implement a file uploader, where a HTML input file is sent by a WebSocket to a Nodejs server.

Tried to read the file in a BLOB and binary string from the FileReader API of HTML and sent it to Nodejs server so it can be written to a file in the server. Tried createWriteStream and writeFile with ascii or base 64 encoding in the Nodejs part.

Still the file saved in server doesn't work properly.

Am I missing something?

Thank you

UPDATE

Client

    var uploader = $("#uploader"),
        files = uploader.prop('files'),
        file_reader = new FileReader();
    file_reader.onload = function(evt) {
        socketClient.write({
            'action': 'ExtensionSettings->upload', 
            'domain': structureUser.domain, 
            'v_id': ext, 
            'file': file_reader.result
        });
    };
    file_reader.readAsDataURL(files[0]);
    //readAsDataURL
    uploader.replaceWith(uploader.clone());

Server

var stream = fs.createWriteStream("file");
stream.once("open", function() {
    stream.write(msg.file, "base64");
    stream.on('finish', function() {
        stream.close();
    });
});

Upvotes: 12

Views: 9067

Answers (3)

tgoneil
tgoneil

Reputation: 1624

Consider starting a separate http server on a different port being used by the websocket and then upload the file via traditional post action in a form. Returning status code 204 (no content) ensures the browser doesn't hang after the post action. The server code assumes directory 'upload' already exists. This worked for me:

Client

<form method="post" enctype="multipart/form-data" action="http://localhost:8080/fileupload">
    <input name="filename" type="file">
    <input type="submit">
</form>

Server

http = require('http');
formidable = require('formidable');
fs = require('fs');

http.createServer(function (req, res) {

    if (req.url === '/fileupload') {

        var form = new formidable.IncomingForm();
        form.parse(req, function (err, fields, files) {
            var prevpath = files.filename.path;
            var name = files.filename.name;
            var newpath = './upload/' + name;

            var is = fs.createReadStream(prevpath);
            var os = fs.createWriteStream(newpath);

                // more robust than using fs.rename
                // allows moving across different mounted filesystems
            is.pipe(os);

                // removes the temporary file originally 
                // created by the post action
            is.on('end',function() {
                fs.unlinkSync(prevpath);
            });

                // prevents browser from hanging, assuming
                // success status/processing
                // is handled by websocket based server code
            res.statusCode = 204;
            res.end();

        });

    }

})
.listen (8080);

Upvotes: 2

user3363398
user3363398

Reputation: 1120

When you stream data in nodejs you do not use write() but instead use pipe(). So once you have your write stream as you did: var stream = fs.createWriteStream("file"); then you pipe() to it as in: sourcestream.pipe(stream); But since the file is being transferred over the internet, your file will be sent in packets and so it will not arrive all at once but instead in pieces, you have to use a buffer array and manually count the data chunks.

You can learn the details here: http://code.tutsplus.com/tutorials/how-to-create-a-resumable-video-uploade-in-node-js--net-25445

There is a module available too that is very easy to use and probably what you want: https://github.com/nkzawa/socket.io-stream

If you didn't care necessarily about going over the socket, you can also do it within your client scripts with an ajax form POST using the formidable module on the server to process the form upload: https://github.com/felixge/node-formidable

Upvotes: 0

Jabher
Jabher

Reputation: 328

.readAsDataURL() returns string in format data:MIMEtype;base64,.... you should remove part before comma, as it is not part of base64 encoded file, it's service data

Upvotes: 2

Related Questions