admin管理员组

文章数量:1279055

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();
    });
});

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();
    });
});
Share Improve this question edited Jul 1, 2017 at 5:04 kerrigan 872 silver badges9 bronze badges asked Dec 16, 2013 at 16:16 user2448953user2448953 1211 silver badge4 bronze badges 5
  • Please send us the client and server code, it's hard to guess what you did wrong without it! – Paul Mougel Commented Dec 16, 2013 at 16:28
  • Can you capture packet on server? – damphat Commented Dec 16, 2013 at 16:55
  • the easy way is to rip into a base64 on the client using a dataURL and ship that b64 string to node where you write atob(str.split(",")[1]) to a file using binary mode (not uft8 or base64). if you get more hard-core and only need to support newer browsers, you can actually ship an un-added binary blob using Socket.send() developer.mozilla/en-US/docs/Web/API/WebSocket#send() – dandavis Commented Dec 16, 2013 at 16:59
  • 6 @user2448953 For what it's worth, you might consider using BinaryJS (github./binaryjs/binaryjs) to set up streams you can more easily read/write from. One of the samples includes doing exactly what you are doing here. – Brad Commented Dec 16, 2013 at 17:52
  • Agree with Brad, binaryjs does exactly same thing. You are trying to write the code from scratch and then debug it. – user568109 Commented Dec 17, 2013 at 5:31
Add a ment  | 

3 Answers 3

Reset to default 2

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

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.IningForm();
        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);

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./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./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./felixge/node-formidable

本文标签: javascriptUpload Files with Websockets and NodejsStack Overflow