2010-09-16 68 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或雙方都知道的另一個唯一標識符。