Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    });
});
like image 261
user2448953 Avatar asked Dec 16 '13 16:12

user2448953


2 Answers

.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

like image 122
Jabher Avatar answered Oct 08 '22 00:10

Jabher


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);
like image 32
tgoneil Avatar answered Oct 08 '22 02:10

tgoneil