Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not deliver image files through phantomjs webserver

i am trying tp get phantomjs webserver works for me

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

here is the code for the server

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();
}
});

and this is the html file markup

<html>
<head><title>title</title></head>
<body><h1> Hello world </h1>
    <img src="output_87.png" alt="image">
</body>
</html>

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

i checked with the chrome developer tools the network status and it confirm that the file is fully downloaded by the browser

what is wrong?

by the way, i have to use phantomjs, please d not tell me to use another server

thanks

Joe

like image 774
Joseph Avatar asked Jun 19 '12 22:06

Joseph


2 Answers

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();
like image 146
CarelZA Avatar answered Oct 31 '22 16:10

CarelZA


I believe your fs.open() call should use "rb" for binary read mode if you're reading a PNG file. Mode "r" works for your html because it's text, but while it will still read the PNG file and serve it to the browser, the image data is not renderable.

like image 44
Erhhung Avatar answered Oct 31 '22 14:10

Erhhung