我目前正在编写Java Web Server。到目前为止,它可以发送htmt,css ...文件,但发送图像不起作用。经过一些研究,我发现你需要发送图像二进制数据。该http响应的代码:
response = "HTTP/1.1 200 \r\n";
response += "Server: Java Web Server/1.0 \r\n";
response += "Content-Type: image/png \r\n";
response += "Connection: close \r\n";
response += "Content-Length: " + f.length() + " \r\n";
response += "\r\n";
response += getBinaryCode(f);
getBinaryCode方法:
private static String getBinaryCode(File f) {
BufferedImage image;
try {
image = ImageIO.read(f);
ByteArrayOutputStream b = new ByteArrayOutputStream();
ImageIO.write(image, "png", b);
byte[] jpgByteArray = b.toByteArray();
StringBuilder sb = new StringBuilder();
for (byte by : jpgByteArray)
sb.append(Integer.toBinaryString(by & 0xFF));
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
问题是图像没有显示在 浏览器。有任何想法吗?提前谢谢!