nodejs读取图片返回给浏览器显示

来源:互联网 发布:河南漯河网络电视台 编辑:程序博客网 时间:2024/05/04 05:04

本文主要是使用nodejs处理图片等资源返回给浏览器显示方法,但不只限制于图片,也可以是音频视频等其他非字符串文件的返回和显示。也可以扩展成nodejs静态资源服务器的开发方法。

请求头说明

在http响应里面有几个重要的东西,Content-Type 说明文件渲染MIME类型,这是我们本文的相关处理关键。

常用的MIME类型

{  "css": "text/css",  "gif": "image/gif",  "html": "text/html",  "ico": "image/x-icon",  "jpeg": "image/jpeg",  "jpg": "image/jpeg",  "js": "text/javascript",  "json": "application/json",  "pdf": "application/pdf",  "png": "image/png",  "svg": "image/svg+xml",  "swf": "application/x-shockwave-flash",  "tiff": "image/tiff",  "txt": "text/plain",  "wav": "audio/x-wav",  "wma": "audio/x-ms-wma",  "wmv": "video/x-ms-wmv",  "xml": "text/xml"}

处理方法

一、静态返回资源
原理:
使用node.js的fs.readFile来处理。根据请求地址,转换成实际的文件地址。判断文件是否存在,不存在返回404,存在则读取文件 ,并返回文件

//设置请求的返回头type,content的type类型列表见上面response.setHeader("Content-Type", contentType);//格式必须为 binary 否则会出错var content =  fs.readFileSync(url,"binary");   response.writeHead(200, "Ok");response.write(content,"binary"); //格式必须为 binary,否则会出错response.end();

二、动态文件流处理
原理:
使用nodejs 的fs.createReadStream来处理,这样处理的好处是断点续传。

response.set( 'content-type', mimeType );//设置返回类型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();    });}
  1. 客户端读取文件 var content = fs.createReadStream(filePath);
  2. 把内容转为数组 var buffer = new Buffer(content); 传给 httpServer这一步需要特别注意,一定不能把 content 当成普通的字符串处理传给 httpServer
  3. httpServer 解析出数组 var list = …
  4. httpServer 把数组转为 Buffer, var buffer = new Buffer(list);
  5. 返回 response.write(buffer.toString(),”binary”); //注意,这里必须转为字符串,不能以 Buffer 传给浏览器.
  6. 值得注意的是,这里的 buffer 不能直接返回给客户端,nodejs 以 binary 格式读取的文件就是一个字符串,只是编码不是普通的 utf-8
0 0