2017-02-04 86 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