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/');
})

  

nodejs服务器读取图片返回给前端(浏览器)显示的更多相关文章

  1. python opencv 读取图片 返回图片某像素点的b,g,r值

    转载:https://blog.csdn.net/weixin_41799483/article/details/80884682 #coding=utf-8   #读取图片 返回图片某像素点的b,g ...

  2. Nodejs koa2读取服务器图片返回给前端直接展示

    参考:https://blog.csdn.net/lihefei_coder/article/details/105435358 const fs = require('fs'); const pat ...

  3. vue中图片返回404时,显示默认的图片

    图片返回404时候的处理 <img :src="userMsg.portrait" ref="img" alt=""> _thi ...

  4. img标签插入图片返回403,浏览器可以直接打开

    参考:https://segmentfault.com/q/1010000011752614/a-1020000011764026 博客园引入外部图片出现,出现403问题,应该是加了防盗链,会检测访问 ...

  5. NodeJS服务器退出:完成任务,优雅退出

    上一篇文章,我们通过一个简单的例子,学习了NodeJS中对客户端的请求(request)对象的解析和处理,整个文件共享的功能已经完成.但是,纵观整个过程,还有两个地方明显需要改进: 首先,不能共享完毕 ...

  6. img src某个php文件输出图片(回复更改图片readfile读取图片等)

    在论坛我们经常看到一回复图片就更改等,这功能是怎么实现的呢,其实更验证码道理相同. 新建文件 randimage.php 加入以下代码: <?php $dir='../../images/'; ...

  7. JAVA实现读取图片

    话不读说  直接上代码 package cn.kgc.ssm.common; import java.io.*; /** * @author * @create 2019-08-15 9:36 **/ ...

  8. ios 向sqlite数据库插入和读取图片数据

    向sqlite数据库插入和读取图片数据 (for ios) 假定数据库中存在表 test_table(name,image), 下面代码将图片文件test.png的二进制数据写到sqlite数据库: ...

  9. spring从服务器磁盘读取图片,然后显示于前端页面上

    需求是,前台通过传参,确定唯一图片,然后后台在服务器磁盘中读取该图片,然后显示于前台页面上. 后台代码: @RequestMapping("unit/bill/showeinvoice&qu ...

随机推荐

  1. [luogu4462][异或序列]

    传送门 突然发现自己没整理过异或的知识,正好借这个题整理一下. 关于异或 (1)异或就是在二进制下,两数各个位置上的数,相同为0,不同为1,所得到的数,比如说4^7,4的二进制是100,7的二进制是1 ...

  2. Eclipse导入模板格式Xml配置文件

    Eclipse一般常用的可以导入两处 *.xml 格式的模板,一个是常用的注释格式模板,另一个是代码格式化时用的模板,导入方法如下: 假设: 1.xml 是代码注释格式模板     2.xml 是代码 ...

  3. Cleanup failed to process the following paths错误的解决

    在使用TortoiseSVN工具执行Cleanup操作时经常出现Cleanup failed to process the following paths的错误,具体如下图: 网上搜索了一下,找到了解 ...

  4. nxlog windows安装部署

    nxlog 介绍 nxlog 是用 C 语言写的一个跨平台日志收集处理软件.其内部支持使用 Perl 正则和语法来进行数据结构化和逻辑判断操作.不过,其最常用的场景.是在 windows 服务器上,作 ...

  5. sns.pairplot

    sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...

  6. 编译安装php-7.1.17及部分扩展

    ./configure --prefix=/usr/local/php-7.1.17 --disable-debug --enable-shmop --with-gd --with-jpeg-dir= ...

  7. CentOS6.x下源码安装MySQL5.5

    1. 更新yum源:http://www.cnblogs.com/vurtne-lu/p/7405931.html 2. 卸载原有的mysql数据库 [root@zabbix ~]# yum -y r ...

  8. RocketMQ之消息幂等

    幂等(idempotent.idempotence)是一个数学与计算机学概念,常见于抽象代数中. 在编程中一个幂等操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同. 首先我们了解一下什么是 ...

  9. SpringMVC学习笔记_01

    1.JAVAEE体系结构 JAVAEE体系结构图如下所示: 2.什么是springmvc? 什么是mvc? Model1 Model2 SpringMVC是什么? SpringMVC是一个web层mv ...

  10. XQuartz简介

    这是一个类似于中转的软件,比如现在在Mac上,YY语音还没有官方版的,但其实在Mac上,有了XQuartz就可以实现运行YY了,下载这个从Windows上移植过来的软件,然后打开的时候,Mac会提醒你 ...