2010-09-16 61 views
5

我想用AJAX进度条制作一个Node.js文件上传器。Node.js AJAX文件上传器

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有什么想法吗? 我将如何请求文件上传的状态?

谢谢,亚历克斯

+0

我无法回答这个问题,但一定要停下[#node.js](http://webchat.freenode.net/?channels=node.js&uio=d4)并提出问题! – DTrejo 2011-03-30 04:46:03

+0

你解决了吗? – 2011-05-25 13:16:16

+0

可悲的是,没有空闲时间..这可能有助于https://github.com/felixge/node-formidable或检查felixge的可调试博客文章,他涵盖了这些问题的很多。 – Alex 2011-05-26 13:13:05

回答

1

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

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

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

0

为了刚刚回答问题THRID

我怎么会请求文件上传状态?

厉害有一个事件“陆侃”:

Event: 'progress' (bytesReceived, bytesExpected) 

有了这个,你可以很容易地保持你的进步轨迹,并返回它在你准备更新呼叫。

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