【每日一題NO.70】Node中處理文件上傳


問題:
當我們前端調(diào)用文件上傳接口的時候,Node服務中如何可以拿到上傳的文件內(nèi)容?
http.createServer
在不使用Node框架的情況下,我們可以使用 http 模塊自帶的 createServer函數(shù)[1]。
基本用法:
const?http?=?require('http');
//?創(chuàng)建本地服務器來從其接收數(shù)據(jù)
const?server?=?http.createServer((request,?response)?=>?{
??console.log(request)
??//?設置響應頭,當同時使用了response.setHeader()?和 response.writeHead()?時,所有設置會被合并到一起,且 response.writeHead()?的設置優(yōu)先。
??response.writeHead(200,?{?'Content-Type':?'application/json'?});?
??//?返回一個JSON字符串,有data屬性值為'Hello?World!'
??response.end(JSON.stringify({
????data:?'Hello?World!'
??}));
});
server.listen(8000);?//?啟動服務后訪問?http://localhost:8000/
傳入請求對象的 request,其實已經(jīng)實現(xiàn)了 ReadableStream 接口,這個信息流可以被監(jiān)聽或者與其它流進行對接。我們可以監(jiān)聽 data 和 end 事件從而把數(shù)據(jù)給取出來。
獲取到上傳文件的內(nèi)容代碼如下:
const?http?=?require('http');
let?fileData?=?'';
http.createServer((request,?response)?=>?{
??request
????.on('error',?(err)?=>?{
??????console.error(err);
????})
????.on('data',?(chunk)?=>?{
??????//?在data中拼接分段的流數(shù)據(jù)
??????fileData?+=?data;
????})
????.on('end',?()?=>?{
?????// end事件回調(diào)時說明拼接結(jié)束,拿到完整數(shù)據(jù)。
??????console.log('得到最終文件結(jié)果:',?fileData);
????});
}).listen(8080);
文件流
文件的內(nèi)容不是一次性的傳過來,是以 流[2] 的方式傳輸?shù)摹?/p>
流數(shù)據(jù)是一組順序、大量、快速、連續(xù)到達的數(shù)據(jù)序列,可理解為一個動態(tài)數(shù)據(jù)集合。
意象理解:一個文件就像一塊冰,我們要進行服務器之間網(wǎng)絡傳輸時,需要講冰化成水,一點點倒給網(wǎng)絡水槽,從A杯子通過水管流到B杯子,水流匯集完畢后再存儲成一塊冰。
Content-Type
注意文件上傳時,請求頭里的 Content-Type字段[3] 對應的值應該是multiparty/form-data; boundary=something。
參考資料
[1]createServer函數(shù): http://nodejs.cn/api/http.html#http_http_createserver_options_requestlistener
[2]流數(shù)據(jù)·百度百科: https://baike.baidu.com/item/%E6%B5%81%E6%95%B0%E6%8D%AE/7418273?fr=aladdin
[3]Content-Type字段: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Type
所有《每日一題》的 知識大綱索引腦圖 整理在此:https://www.yuque.com/dfe_evernote/interview/everyday
你也可以點擊文末的 “閱讀原文” 快速跳轉(zhuǎn)

END愿你歷盡千帆,歸來仍是少年。
