我正在尝试使用AJAX进度条制作一个Node.js文件上传器。
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很长,所以我已经删掉了它,但是它所做的只是启动一个计时器,并从更新中请求数据并在标签上进行设置。
使用此代码, Node 将接受来自不同主机的多个上传吗?
Firefox似乎也不起作用,但是Safari/Chrome有什么想法吗?
我将如何请求文件上传的状态?
谢谢,亚历克斯
最佳答案
您需要做的一件事是一种唯一地标识特定上载的方法。该表单应包含一个唯一ID,作为标识上传的隐藏字段。然后,在进行上传时,您可以保留ID->进度级别的映射,并且“update”调用将传递该ID以确保它正在查看正确的进度指示器。
但是,您可能会发现,浏览器仅允许有限数量的服务器连接。因此,您对进度更新的请求可能会等待实际上传完成,甚至还没有发送到服务器。
为了解决这个问题,您可能需要使用socket.io在开始上载之前打开与保持打开状态的服务器的连接,并随着上载的进行在该连接上接收更新。
关于javascript - Node.js AJAX文件上传器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3725928/