1 前言
項目需要用nodejs服務器給前端傳遞圖片,網上找了好多資料,多數都是怎么在前端上傳圖片的,然后通過看runoob.com菜鳥教程,發現其實是非常簡單,用express框架就行了。
2 代碼
2.1 用原生的版本(包含了返回網頁功能)
var http = require('http'); var fs = require('fs'); var url = require('url'); // 創建服務器 http.createServer( function (request, response) { // 解析請求,包括文件名 var pathname = url.parse(request.url).pathname; // 輸出請求的文件名 console.log("Request for " + pathname + " received."); // 從文件系統中讀取請求的文件內容 fs.readFile(pathname.substr(1), function (err, data) { var urlContent = pathname.substr(1); if(urlContent.lastIndexOf("png") > -1){ if (err) { console.log(err); // HTTP 狀態碼: 404 : NOT FOUND // Content Type: text/plain response.writeHead(404, {'Content-Type': 'text/html'}); }else{ // HTTP 狀態碼: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'image/png'}); var imageFilePath = pathname.substr(1); var stream = fs.createReadStream( imageFilePath ); var responseData = [];//存儲文件流 if (stream) {//判斷狀態 stream.on( 'data', function( chunk ) { responseData.push( chunk ); }); stream.on( 'end', function() { var finalData = Buffer.concat( responseData ); response.write( finalData ); response.end(); }); } } }else if(urlContent.lastIndexOf("html") > -1){ if (err) { console.log(err); // HTTP 狀態碼: 404 : NOT FOUND // Content Type: text/plain response.writeHead(404, {'Content-Type': 'text/html'}); }else{ // HTTP 狀態碼: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/html'}); // 響應文件內容 response.write(data.toString()); } // 發送響應數據 response.end(); }else{ console.log("unSupport Type, Please contact Administrator err url="+urlContent); } }); }).listen(80);
2.2 用Express框架版本
var express = require('express'); var app = express(); app.use(express.static('public')); app.get('/public/images/*', function (req, res) { res.sendFile( __dirname + "/" + req.url ); console.log("Request for " + req.url + " received."); }) app.get('/public/html/index.html', function (req, res) { res.sendFile( __dirname + "/" + "/public/html/index.html" ); console.log("Request for " + req.url + " received."); }) //如果訪問網頁和本地同名,可以使用以下版本 app.get('/public/html/*.html', function (req, res) { res.sendFile( __dirname + "/" + req.url ); console.log("Request for " + req.url + " received."); }) app.get('/public/register', function (req, res) { res.sendFile( __dirname + "/" + "/public/html/register.html" ); console.log("Request for " + req.url + " received."); }) var server = app.listen(80, function () { console.log('Server running at http://127.0.0.1:80/'); })