无法通过phantomjs webserver传递图像文件 [英] Can not deliver image files through phantomjs webserver
问题描述
我正在尝试获取phantomjs webserver为我工作
i am trying tp get phantomjs webserver works for me
我想提供2个文件,html文件和png图像文件,html文件很好用并在浏览器中正确呈现,但png文件不是
I want to serve 2 files, html file , and a png image file, the html file is served well and rendered correctly in the browser, but the png file is not
这里是服务器的代码
var fs = require('fs');
function loadFile(name){
if(fs.exists(name)){
console.log(name+ " File exist");
return fs.open(name,"r");
}else {
console.log("File do not exist");
}
}
var server, service;
server = require('webserver').create();
service = server.listen(8080, function (request, response) {
if(request.url.split(".")[1] === "html" ){
var fi = loadFile("./test.html");
response.statusCode = 200;
response.write(fi.read());
fi.close();
response.close();
}else if (request.url.split(".")[1] === "png"){
var fi = loadFile("./output_87.png");
response.headers = {"Content-Type":"image/png"};
response.statusCode = 200;
response.write(fi.read());
fi.close();
response.close();
}
});
这是html文件标记
<html>
<head><title>title</title></head>
<body><h1> Hello world </h1>
<img src="output_87.png" alt="image">
</body>
</html>
在浏览器中查看此文件时,png文件未呈现,即使我尝试将浏览器指向png文件,它不会呈现它
when viewing this file in the browser, the png file is not rendered, and even if i tried to point the browser to the png file, it does not render it
我使用chrome developer工具检查了网络状态,并确认浏览器已完全下载该文件
i checked with the chrome developer tools the network status and it confirm that the file is fully downloaded by the browser
出了什么问题?
顺便说一下,我必须使用phantomjs,请不要告诉我使用另一台服务器
by the way, i have to use phantomjs, please d not tell me to use another server
谢谢
Joe
推荐答案
这对我有用(假设你有响应对象):
This works for me (assuming you have the response object):
var fs = require("fs");
var image = fs.open("image.png", "rb");
var data = image.read();
image.close();
response.setHeader("Content-Type", "image/png");
response.setEncoding("binary");
response.write(data);
response.close();
这篇关于无法通过phantomjs webserver传递图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!