我有一个服务器文件,用于上传文件和在主页面实现聊天。问题是multer文件上传不能与http.listen()
一起使用app.listen()
,而另一个包socket.io只能与http.listen()
一起使用,所以我只能使用var express = require("express");
var fs = require('fs');
var multer = require('multer');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
app.set("view engine","ejs");
var fileinfo = [];
var dir = __dirname +"\\files\\";
//storage for multer with destination and filename
some code here
var upload = multer({storage: storage}).array('newfile',50);
//home page checks for files in the files folder and passes file info to home.ejs
code here.route for home page
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log("message recieved" + msg);
io.emit('chat message', msg);
});
});
// route to download files
app.get('/download/:namefile', function(req, res){
// console.log("hey man" + req.params.namefile);
var file = dir + req.params.namefile;
// var filestream = fs.createReadStream(file);
// filestream.pipe(res);
res.download(file);
});
//route to upload files. It used upload method defined above to upload the files via multer
app.post("/uploadfile",function(req,res){
upload(req, res, function(err) {
if(err) {
console.log('Error Occured ' + err);
return;
}
console.log(req.files);
res.end('Your Files Uploaded');
})
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
聊天或文件上传工作。
这是有用的代码:
getIt
目前正在进行聊天。