node-读取图片,content-type如何设置

在使用node读取图片并加载到页面时,值得注意的是content-type的值不同,会得到不同的结果,content-type的值尤为关键

一、常见content-type的值

1.text/html
2.text/plain
3.text/css
4.text/javascript
5.application/x-www-form-urlencoded   post  $.post 
6.multipart/form-data   form action  method='post'  
7.application/json
8.application/xml

二、解析的图片需要注意的点

解析图片时需要设置的值为images/jpeg或者image/jpeg,此处就是关键所在了

  • images/jpeg
    • 返回给前端的是完整的图片展示
  • image/jpeg
    • 直接开始下载图片到本地

三、主要功能代码

1、判断图片是否存在

//查询文件夹中是否存在该名字的图片,不存在则404,存在则读取图片
var data = fs.readdirSync('./images');
    if (data.indexOf(path) == -1) {
       res.write('<h1>404-页面未找到</h1>');
    } else {
       res.writeHead(200, {
           'Content-type': 'image/jpeg'
       })
       file('./images/' + path, req, res);
    }

2、读取二进制图片内容,并返回

function file(path, req, res) {
     //banary二进制
    fs.readFile(path, 'binary', (err, data) => {
       res.write(data, 'binary');
       res.end();
    })
}

posted @ 2020-07-15 18:00  飘逸_winxin  阅读(1937)  评论(0编辑  收藏  举报