1 前言
项目需要用nodejs服务器给前端传递图片,网上找了好多资料,多数都是怎么在前端上传图片的,然后通过看runoob.com菜鸟教程,发现其实是非常简单,用express框架就行了。
2 代码
2.1 用原生的版本(包含了返回网页功能)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
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框架版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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/‘ ); }) |