您的位置:首页 > Web前端 > Node.js

Node.js使用fs模块实现对本地图片下载

2018-03-12 00:18 615 查看
使用node.js自带的http模块与fs模块搭建了一个可以下载图片的服务器。
项目的github:https://github.com/junhaogz215/getImage
效果如下:
运行服务器之后在地址栏输入http://localhost:3000可跳转到index.html首页



点击下载图片即可下载相应图片:



源码
index.html:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
box-sizing: border-box;
}

body {
padding: 20px 20px;
}

li {
list-style: none;
width: 20%;
float:left;
}

li {
margin-right: 5%;
}

li img {
width: 100%;
}

a {
/* display: block; */
padding: 5px 10px;
background: rgb(36, 152, 165);
border-radius: 4px;
color: #ffffff;
text-decoration: none;
}

figcaption {
margin: 10px 0;
}
</style>
</head>
<body>
<ul>
<li>
<figure>
<img src="./images/cat1.jpg" alt="cat1.jpg">
<figcaption><a href="http://localhost:3000/images/cat1.jpg">下载图片</a></figcaption>
</figure>
</li>
<li>
<figure>
<img src="./images/cat5.jpg" alt="cat1.jpg">
<figcaption><a href="http://localhost:3000/images/cat5.jpg">下载图片</a></figcaption>
</figure>
</li>
<li>
<figure>
<img src="./images/cat7.jpg" alt="cat1.jpg">
<figcaption><a href="http://localhost:3000/images/cat7.jpg">下载图片</a></figcaption>
</figure>
</li>
<li>
<figure>
<img src="./images/chuyin.jpg" alt="cat1.jpg">
<figcaption><a href="http://localhost:3000/images/chuyin.jpg">下载图片</a></figcaption>
</figure>
</li>
</ul>
</body>
</html>getImage.jsvar http = require('http'),
fs = require('fs')

var server = http.createServer((req, res) => {
if ('GET' == req.method
&& '/images' == req.url.substr(0, 7)
&& '.jpg' == req.url.substr(-4)) {
fs.stat(__dirname + req.url, (err, stat) => { //该回调函数用来判断请求的资源是否为文件如果不是文件返回404
if (err || !stat.isFile()) {
res.writeHead(404);
res.end('Not Found');
return;
}
serve(__dirname + req.url, 'application/jpg');
});
} else if ('GET' == req.method && '/' == req.url) {
serve(__dirname + '/index.html', 'text/html');
} else {
res.writeHead(404);
res.end('Not Found');
}

//用来读取文件并把文件响应给服务器
function serve (path, type) {
res.writeHead(200, {'content-type': type});
fs.createReadStream(path)
.on('data', data => res.write(data))
.on('end', () => res.end());
}

}) .listen(3000);

server.listen(3000, () => {
console.log('服务器启动成功,端口号:3000')
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  node.js javascript html css