nodejs服务器读取图片返回给前端(浏览器)显示
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服务器读取图片返回给前端(浏览器)显示的更多相关文章
- python opencv 读取图片 返回图片某像素点的b,g,r值
转载:https://blog.csdn.net/weixin_41799483/article/details/80884682 #coding=utf-8 #读取图片 返回图片某像素点的b,g ...
- Nodejs koa2读取服务器图片返回给前端直接展示
参考:https://blog.csdn.net/lihefei_coder/article/details/105435358 const fs = require('fs'); const pat ...
- vue中图片返回404时,显示默认的图片
图片返回404时候的处理 <img :src="userMsg.portrait" ref="img" alt=""> _thi ...
- img标签插入图片返回403,浏览器可以直接打开
参考:https://segmentfault.com/q/1010000011752614/a-1020000011764026 博客园引入外部图片出现,出现403问题,应该是加了防盗链,会检测访问 ...
- NodeJS服务器退出:完成任务,优雅退出
上一篇文章,我们通过一个简单的例子,学习了NodeJS中对客户端的请求(request)对象的解析和处理,整个文件共享的功能已经完成.但是,纵观整个过程,还有两个地方明显需要改进: 首先,不能共享完毕 ...
- img src某个php文件输出图片(回复更改图片readfile读取图片等)
在论坛我们经常看到一回复图片就更改等,这功能是怎么实现的呢,其实更验证码道理相同. 新建文件 randimage.php 加入以下代码: <?php $dir='../../images/'; ...
- JAVA实现读取图片
话不读说 直接上代码 package cn.kgc.ssm.common; import java.io.*; /** * @author * @create 2019-08-15 9:36 **/ ...
- ios 向sqlite数据库插入和读取图片数据
向sqlite数据库插入和读取图片数据 (for ios) 假定数据库中存在表 test_table(name,image), 下面代码将图片文件test.png的二进制数据写到sqlite数据库: ...
- spring从服务器磁盘读取图片,然后显示于前端页面上
需求是,前台通过传参,确定唯一图片,然后后台在服务器磁盘中读取该图片,然后显示于前台页面上. 后台代码: @RequestMapping("unit/bill/showeinvoice&qu ...
随机推荐
- A1091. Acute Stroke
One important factor to identify acute stroke (急性脑卒中) is the volume of the stroke core. Given the re ...
- A1103. Integer Factorization
The K-P factorization of a positive integer N is to write N as the sum of the P-th power of K positi ...
- [poj1275][Cashier Employment]
poj1275 题目大意: 每天有24小时,每个小时需要一定的人.有m个人每个人会有一个开始工作的时间,每个人会工作8小时,问至少需要多少人才能完成任务.如果这m个人也不能完成任务就输出"N ...
- MIME 类型(HttpContext.Response.ContentType)列表
按照内容类型排列的 Mime 类型列表 类型/子类型 扩展名 application/envoy evy application/fractals fif application/futurespla ...
- 有趣的filter
js中的filter就是过滤的意思,比如,我们以什么样的方式进行过滤,得到我们想要的结果. 对,我们要的就是这个结果. 给定一个数组,我们要的是Burger(汉堡) const restaurants ...
- 用c语言实现http请求
用c语言来实现一个简单的http请求,请求 www.cnblogs.com 首页 #include<stdio.h> #include<stdlib.h> #include&l ...
- shell中的循环语法
shell中的循环语法 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.for循环 1.语法格式1 for 变量 in 值1 值2 值3 ... do ...
- Linux操作系统原理
Linux操作系统原理 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.计算机经历的四个时代 1.第一代: 真空管计算机,输入和输出:穿孔卡片,对计算机操作起来非常不便,做一件事 ...
- python---RabbitMQ(2)exchange中订阅者模式fanout<广播>,(一对多,发布一条消息,多人同时接收)
fanout:广播:所有bind到此exchange的queue都可以接受到消息 生产者: # coding:utf8 # __author: Administrator # date: // # / ...
- vue基础篇---路由的实现
路由可以有两种实现方式,一种是标签形式的,一种是js实现. 标签: <router-link to='/city'> 北京 </router-link> 标签还有另外一种实现方 ...