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. 【洛谷P2607】骑士 没有上司的舞会+

    题目大意:给定一个 N 个点的外向树森林,点有点权.从该树中选出若干顶点组成一个集合,满足任意相邻的两个顶点不同时出现在该集合中,求这样集合中点权和的最大值为多少. 题解:与树相比,该题多了环这个结构 ...

  2. 文件操作(十二)——open,read,close,write,seek,truncate

    open函数 #!/usr/bin/env python #-*- coding:utf8 -*- f = open('xxx','r',encoding='utf-8') data = f.read ...

  3. 浏览器中输入URL发生了什么

    浏览器中输入URL会发生什么呢?这是我们经常会问到的一个问题. 我们知道的都是会发送http请求,服务端会处理请求给我们响应的结果,浏览器会渲染html 页面 但其实会遗漏掉一些比较重要的东西.下面的 ...

  4. 论C++的发家史以及相对其他语言优缺

    C++发家史: 最初导致C++诞生的原因是在Bjarne博士等人试图去分析UNIX的内核的时候,这项工作开始于1979年4月,当时由于没有合适的工具能够有效的分析由于内核分布而造成的网络流量,以及怎样 ...

  5. Myeclipse 2017 安装与破解

    前言:今天的 Myeclipse 2017 不能用了. 直接找一个教程,破解了,教程的地址如下: http://blog.csdn.net/qingjianduoyun/article/details ...

  6. jenkins+gitlab webhooks 实现自动触发打包

    说明:实现代码在gitlab上的提交后立马自动进行jenkins的job构建 安装插件: Gitlab Hook Plugin  Build Authorization Token Root Plug ...

  7. 百度编辑器 Ueditor 如何增加模板 ?

    模板文件在这里: dialogs/template/config.js 参见:http://t.mreald.com/191 .

  8. This page is about building Firefox Desktop

    This page is about building Firefox Desktop The Mozilla build system, like the rest of the Mozilla c ...

  9. beef框架使用

    http://resources.infosecinstitute.com/beef-part-2/ http://resources.infosecinstitute.com/beef-part-1 ...

  10. sonar扫描java、js、jsp技术

    最近在弄sonar扫描的事情,之前一直只能扫描java代码,这样统计出来的数据上报领导很多开发人员不服(说我不用写jsp了不用写js了?), 那么好,于是乎继续整sonar,在官网中看到sonar其实 ...