静态图片文件输出错误的问题
发布于 12 年前 作者 shaman 10673 次浏览 最后一次编辑是 8 年前

静态文件的读取是参照Jackson的文章 用NodeJS打造你的静态文件服务器

var http = require("http");
var fs = require("fs");
var url = require("url");
var path = require("path");
var mine = require("./mime");

http.createServer(function(req, res){
var pathname = url.parse(req.url).pathname;
var ext = path.extname(pathname) || "unknow";
fs.readFile(__dirname + pathname, "utf8", function(err, content){
    if(!err){
        res.writeHead(200, {
            'Content-Type': mine.types[ext]
        });
        res.write(content);
        res.end();
    }
   });
 }).listen(8080, function(){
  console.log("server started");
 })

mime.js:

exports.types = {
".css" : "text/css",
".html" : "text/html",
".js" : "text/javascript",
".png" : "image/png",
".gif" : "image/gif",
".jpg" : "image/jpg",
".jpeg" : "image/jpeg",
".ico" : "image/x-icon",
"unknow" : "text/plain"
}

在我访问localhost:8080/index.html的时候html文件,js文件,json文件都没问题,但是图片的请求都抛出这样的错误:

Image corrupt or truncated: http://localhost:8080/static/images/black_che.png
Image corrupt or truncated: http://localhost:8080/static/images/black_ma.png
Image corrupt or truncated: http://localhost:8080/static/images/black_xiang.png
Image corrupt or truncated: http://localhost:8080/static/images/black_shi.png
Image corrupt or truncated: http://localhost:8080/static/images/black_jiang.png
Image corrupt or truncated: http://localhost:8080/static/images/black_pao.png
Image corrupt or truncated: http://localhost:8080/static/images/black_zu.png
Image corrupt or truncated: http://localhost:8080/static/images/red_pao.png
Image corrupt or truncated: http://localhost:8080/static/images/red_bing.png
Image corrupt or truncated: http://localhost:8080/static/images/red_che.png
Image corrupt or truncated: http://localhost:8080/static/images/red_ma.png
Image corrupt or truncated: http://localhost:8080/static/images/red_xiang.png
Image corrupt or truncated: http://localhost:8080/static/images/red_shi.png
Image corrupt or truncated: http://localhost:8080/static/images/red_shuai.png

这里对图片静态文件需要做什么额外处理吗?

4 回复

读取图片文件时,直接以Buffer方式读出,不要指定字符编码:

fs.readFile(__dirname + pathname, function(err, content){
  // ....
});

你代码中的s.readFile(__dirname + pathname, "utf8", ...)是不对的

额 ,问题解决了,是自己没认真看代码 :(,用"binary"读取,"binary"输出。

嗯嗯 已经搞定了

我的代码是在readLine函数里面指定编码是"binary",在write函数里面输出制定编码方式是"binary",但是图片不能正确显示,但是去掉readLine函数里面的第二个参数,就是编码方式"binary",图片却能正确显示。不知道为什么,求解?

回到顶部