gpt4 book ai didi

javascript - Node.js AJAX 文件 uploader

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:13 26 4
gpt4 key购买 nike

我正在尝试制作一个带有 AJAX 进度条的 Node.js 文件 uploader 。

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 -> 进度级别的映射,“更新”调用将传递该 ID 以确保它正在查看正确的进度指示器。

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

要绕过它,您可能需要使用 socket.io在开始上传之前打开与保持打开状态的服务器的连接,并在上传过程中接收该连接上的更新。

关于javascript - Node.js AJAX 文件 uploader ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3725928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com