本節我們將實現,用戶上傳圖片,並將該圖片在瀏覽器中顯示出來。
這裡我們要用的外部模組是Felix Geisendörfer開發的node-formidable模組。它對解析上傳的文件資料做了很好的抽象。
要安裝這個外部模組,需要在cmd下執行指令:
npm install formidable
如果輸出類似的訊息就代表安裝成功了:
npm info build Success: formidable@1.0.14
安裝成功後我們用request引入即可:
var formidable = require(“formidable”);
這裡該模組做的就是將透過HTTP POST請求提交的表單,在Node.js中可以被解析。我們要做的就是建立一個新的IncomingForm,它是對提交表單的抽象表示,之後,就可以用它解析request對象,取得表單中需要的資料欄位。
本文案例的圖片檔案儲存在 /tmp資料夾中。
我們先來解決一個問題:如何才能在瀏覽器中顯示儲存在本機硬碟中的檔案?
我們使用fs模組來將檔案讀取到伺服器中。
我們來新增/showURL的請求處理程序,該處理程序直接硬編碼將檔案/tmp/test.png內容展示到瀏覽器中。當然了,首先需要將該圖片儲存到這個位置才行。
我們隊requestHandlers.js做一些修改:
var querystring = require("querystring"),
fs = require("fs");
function start(response, postData) {
console.log("Request handler 'start' was called.");
var body = ''
''
' 'content="text/html; charset=UTF-8" />'
''
''
''
''
'';
response.writeHead(200, {"Content-Type": "text/html"});
response.write(body);
response.end();
}
function upload(response, postData) {
console.log("Request handler 'upload' was called.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("You've sent the text: " querystring.parse(postData).text);
response.end();
}
function show(response, postData) {
console.log("Request handler 'show' was called.");
fs.readFile("/tmp/test.png", "binary", function(error, file) {
if(error) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(error "n");
response.end();
} else {
response.writeHead(200, {"Content-Type": "image/png"});
response.write(file, "binary");
response.end();
}
});
}
exports.start = start;
exports.upload = upload;
exports.show = show;
我們還需要將這個新的請求處理程序,加入到index.js中的路由映射表中:
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
handle["/show"] = requestHandlers.show;
server.start(router.route, handle);
重新啟動伺服器之後,透過造訪http://localhost:8888/show,就可以看到儲存在/tmp/test.png的圖片了。
好,最後我們要的是:
在/start表單中新增一個檔案上傳元素
將node-formidable整合到我們的upload請求處理程序中,用於將上傳的圖片儲存到/tmp/test.png
將上傳的圖片內嵌到/uploadURL輸出的HTML中
第一項很簡單。只需要在HTML表單中,新增一個multipart/form-data的編碼類型,移除先前的文字區,新增一個檔案上傳元件,並將提交按鈕的文案改為「Upload file」即可。 如下requestHandler.js所示:
var querystring = require("querystring"),
fs = require("fs");
function start(response, postData) {
console.log("Request handler 'start' was called.");
var body = ''
''
' 'content="text/html; charset=UTF-8" />'
''
''
' 'method="post">'
''
''
''
''
'';
response.writeHead(200, {"Content-Type": "text/html"});
response.write(body);
response.end();
}
function upload(response, postData) {
console.log("Request handler 'upload' was called.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("You've sent the text: " querystring.parse(postData).text);
response.end();
}
function show(response, postData) {
console.log("Request handler 'show' was called.");
fs.readFile("/tmp/test.png", "binary", function(error, file) {
if(error) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(error "n");
response.end();
} else {
response.writeHead(200, {"Content-Type": "image/png"});
response.write(file, "binary");
response.end();
}
});
}
exports.start = start;
exports.upload = upload;
exports.show = show;
接下來,我們要完成第二步,我們從server.js開始- 移除對postData的處理以及request.setEncoding (這部分node-formidable本身會處理),轉而採用將request物件傳遞給請求路由的方式:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " pathname " received.");
route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
接下來修改router.js,這次要傳遞request物件:
function route(handle, pathname, response, request) {
console.log("About to route a request for " pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response, request);
} else {
console.log("No request handler found for " pathname);
response.writeHead(404, {"Content-Type": "text/html"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
現在,request物件就可以在我們的upload請求處理程序中使用了。 node-formidable會處理將上傳的檔案儲存到本機/tmp目錄中,而我們需
要做的是確保該檔案保存成/tmp/test.png。
接下來,我們把處理檔案上傳以及重新命名的操作放到一起,如下requestHandlers.js所示:
var querystring = require("querystring"),
fs = require("fs"),
formidable = require("formidable");
function start(response) {
console.log("Request handler 'start' was called.");
var body = ''
''
''
''
''
' 'method="post">'
''
''
''
''
'';
response.writeHead(200, {"Content-Type": "text/html"});
response.write(body);
response.end();
}
function upload(response, request) {
console.log("Request handler 'upload' was called.");
var form = new formidable.IncomingForm();
console.log("about to parse");
form.parse(request, function(error, fields, files) {
console.log("parsing done");
fs.renameSync(files.upload.path, "/tmp/test.png");
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:
");
response.write("

response.end();
});
}
function show(response) {
console.log("Request handler 'show' was called.");
fs.readFile("/tmp/test.png", "binary", function(error, file) {
if(error) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(error "n");
response.end();
} else {
response.writeHead(200, {"Content-Type": "image/png"});
response.write(file, "binary");
response.end();
}
});
}
exports.start = start;
exports.upload = upload;
exports.show = show;
做到這裡,我們的伺服器就全部完成了。
在執行圖片上傳的過程中,有的人可能會遇到這樣的問題:
照成這個問題的原因我猜是由於磁碟分割區導致的,要解決這個問題就需要改變formidable的預設零時資料夾路徑,保證和目標目錄處於同一個磁碟分割區。
我們找到requestHandlers.js的 upload函數,將它做一些修改:
function upload(response, request) {
console.log("Request handler 'upload' was called.");
var form = new formidable.IncomingForm();
console.log("about to parse");
form.uploadDir = "tmp";
form.parse(request, function(error, fields, files) {
console.log("parsing done");
fs.renameSync(files.upload.path, "/tmp/test.png");
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:
");
response.write("
response.end();
});
}
我們增加了一句 form.uploadDir = “tmp”,現在重啟伺服器,再執行上傳操作,問題完美解決。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Dreamweaver Mac版
視覺化網頁開發工具

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

WebStorm Mac版
好用的JavaScript開發工具