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. 1093. Count PAT's

    The string APPAPT contains two PAT's as substrings. The first one is formed by the 2nd, the 4th, and ...

  2. Spring实现文件的上传下载

    背景:之前一直做的是数据库的增删改查工作,对于文件的上传下载比较排斥,今天研究了下具体的实现,发现其实是很简单.此处不仅要实现单文件的上传,还要实现多文件的上传. 单文件的下载知道了,多文件的下载呢? ...

  3. Educational Codeforces Round 42 (Rated for Div. 2) E. Byteland, Berland and Disputed Cities

    http://codeforces.com/contest/962/problem/E E. Byteland, Berland and Disputed Cities time limit per ...

  4. 解决QtCreator中文乱码

    在QT的菜单栏”Tools“ -> "Options" -> "Behavior" -> "File Encoding" ...

  5. java代码示例(3)

    /** * 需求分析:根据输入的天数是否是周六或是周日, * 并且天气的温度大于28摄氏度,则外出游泳,否则钓鱼 * @author chenyanlong * 日期:2017/10/14 */ pa ...

  6. Linux命令之tar

    tar命令 用处:打包,压缩,解压 一.打包 用发:tar + -cvf + 被打包的文件名或者文件夹名  (参数C的意思是打包,参数V的意思是打包时显示信息,参数f的意思是打包后文件的后缀名) 示例 ...

  7. JAVA 远程通讯机制

    在分布式服务框架中,一个最基础的问题就是远程服务是怎么通讯的,在Java领域中有很多可实现远程通讯的技术,例如:RMI.MINA.ESB. Burlap.Hessian.SOAP.EJB和JMS等,这 ...

  8. Linux记录-shell一行代码杀死进程(收藏)

    ps -ef |grep hello |awk '{print $2}'|xargs kill -9

  9. ruby计算完成率

    task_complete = ((task_forms_w.to_f / task_forms_num.to_f)*100).round(2).to_s << "%" ...

  10. Nginx动态添加模块

    前言 有时候要使用已安装好的Nginx的功能时,突然发现缺少了对应模块,故需对其进行动态添加模块. 操作 # 查看已安装模块 [root@kazihuo ~]# nginx -V nginx vers ...