如何在nodeJs中保存文件?

时间:2017-02-07 10:13:11

标签: node.js

我不确定我做对了,但想做下一件事: csend文件通过客户端的webSocket连接并保存在服务器上的某个目录中。如何使用nodejs保存它?

客户方:

<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
<script type="text/javascript">
console.log('test');


var socket = new WebSocket("ws://localhost:8081");



socket.onmessage = function(event) {
var incomingMessage = event.data;
showMessage(incomingMessage);
};


function showMessage(message) {
var messageElem = document.createElement('div');
messageElem.appendChild(document.createTextNode(message));
document.getElementById('subscribe').appendChild(messageElem);
}

function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
    if (x.files.length == 0) {
        txt = "Select one or more files.";
    } else {
        for (var i = 0; i < x.files.length; i++) {
            txt += "<br><strong>" + (i+1) + ". file</strong><br>";
            var file = x.files[i];
            console.log(file);
            if ('name' in file) {
                txt += "name: " + file.name + "<br>";
            }
            if ('size' in file) {
                txt += "size: " + file.size + " bytes <br>";
            }
            socket.send(file);
        }
    }
} 
else {
    if (x.value == "") {
        txt += "Select one or more files.";
    } else {
        txt += "The files property is not supported by your browser!";
        txt  += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead. 
    }
}
document.getElementById("demo").innerHTML = txt;

}

和服务器端,webSocket:

 ws.on('message', function(message) {
 //here I need to save file in uploadFile.path = './files/' + 'fileName' 
 //and get file name    
});

1 个答案:

答案 0 :(得分:3)

为此,您必须使用fs(File system)。节点文件的代码应该是这样的

 ws.on('message', function (message) {
        var fs = require('fs');
        fs.writeFile("/tmp/test", message, function (err) {
            if (err) {
                return console.log(err);
            }
            console.log("The file was saved!");
        });
    });

希望这适合你。