2017-02-04 78 views
3

请注意:我想用vanilla Node做到这一点。获取文件大小,上传和POST请求

我要上传与input type="file" HTML标签的文件,并在同一个表单元素打一个提交按钮input type="submit"并获得字节文件的大小,当我提出一个POST请求。

感谢

+0

你有没有尝试过任何东西! – dNitro

+0

我不知道如何在纯Node.js中做到这一点,这就是为什么我向像你这样的专业人员提出这个问题的原因。 – JohnSnow

+0

有谁知道?! – JohnSnow

回答

1

类似下面应该工作:

var http = require('http'); 

var server = http.createServer(function(req, res) { 
    switch (req.url) { 
    case '/': 
     display_form(req, res); 
     break; 
    case '/upload': 
     show_bytes(req, res); 
     break; 
    default: 
     res.writeHead(404, {'content-Type': 'text/plain'}); 
     res.write('not found'); 
     res.end(); 
     break; 
    } 
}); 
server.listen(3000); 

function display_form(req, res) { 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.write(
    '<form action="/upload" method="post" enctype="multipart/form-data">'+ 
    '<input type="file" name="upload">'+ 
    '<input type="submit" value="Submit">'+ 
    '</form>' 
); 
    res.end(); 
} 

function show_bytes(req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.write(req.headers['content-length'] + ' bytes'); 
    res.end(); 
} 
+0

这确实有效,但字节大小稍微偏离。比实际尺寸略大。这是为什么? – JohnSnow

+0

关于@dNitro的任何建议 – JohnSnow

+1

@JohnNoob,我没有注意到这一点,但似乎每次都会增加约230字节到实际大小的开销。通常**内容长度**标题应与传入正文的大小相同。也许是因为*分块*编码?!我真的不知道。你可能会认为这是一个新问题,也许有人会帮助我们。 – dNitro