Node.js AJAXfile upload

我正在尝试使用AJAX进度条制作Node.jsfile upload器。

var formidable = require('./formidable'), http = require('http'), sys = require('sys'); http.createServer(function(req, res) { if (req.url == '/upload' && req.method.toLowerCase() == 'post') { // parse a file upload var form = new formidable.IncomingForm(); form.uploadDir = './node_uploads'; form.keepExtensions = true; //print the upload status in bytes form.addListener("progress", function(bytesReceived, bytesExpected) { //progress as percentage progress = (bytesReceived / bytesExpected * 100).toFixed(2); mb = (bytesExpected / 1024 / 1024).toFixed(1); sys.print("Uploading "+mb+"mb ("+progress+"%)\015"); }); //enter here after upload complete form.parse(req, function(fields, files) { sys.debug("Upload Complete"); res.writeHead(200, {'content-type': 'text/plain'}); res.write('received upload:\n\n'); res.end()); }); return; } if (req.url == '/update') { res.writeHead(200, {'content-type': 'text/plain'}); res.write('<?xml version="1.0"?><response><status>1</status><message>'+ 000 +'</message> </response>'); res.end(); } // show a file upload form res.writeHead(200, {'content-type': 'text/html'}); res.end ( '<form action="/upload" enctype="multipart/form-data" method="post">' + '<p id="statuslabel"></p><p id="anotherlabel"></p>' + '<input type="text" name="title" id="title"><br>' + '<input type="file" name="upload" multiple="multiple"><br>' + '<input type="submit" value="Upload" id="uploadform">' + '</form>' ); }).listen(8000, '127.0.0.1'); 

jQuery是相当长的,所以我已经把它剪掉了,但是它所做的只是启动一个计时器,并从标签上的更新和设置请求数据。

有了这个代码,节点会接受来自不同主机的多个上传吗? 另外Firefox似乎不工作,但Safari / Chrome有什么想法? 我将如何请求file upload的状态?

谢谢,Alex

你需要的一件事是一种唯一识别特定上传的方法。 表单应该包含一个唯一的ID作为标识上传的隐藏字段。 然后,在上传时,您可以保留一个ID – >进度级别的地图,“更新”调用将传递该ID以确保它正在查看正确的进度指示器。

但是,您可能会发现,浏览器只允许有限数量的服务器连接。 因此,您的进度更新请求可能会等待实际的上传完成,然后才能发送到服务器。

为了解决这个问题,你可能需要使用socket.io打开一个到启动上传前保持打开状态的服务器的连接,并在上传过程中接收连接的更新。

为了回答第三个问题

我将如何请求file upload的状态?

强大的事件“progess”:

 Event: 'progress' (bytesReceived, bytesExpected) 

有了这个,你可以很容易地跟踪你的进度,并在准备好的更新通话中返回。

所以只需在您的更新调用中使用您的ajax进行轮询,例如会话ID或双方都知道的另一个唯一标识符。