我有一个简单的Java Web Server,我正尝试使用它在浏览器中显示图像。
到目前为止,我拥有它,以便在进入localhost:7500 / image2.jpg时,它下载图像而不是在浏览器中显示它
转到gif扩展名(localhost:7500 / image33.gif)时,它只会显示一个很小的黑色正方形。
这是我到目前为止所做的:
public void getType(File f, String path, BufferedReader bfr)
{
String extention = path.substring(path.lastIndexOf("/") + 1);
try {
if (extention == "gif")
{
String line;
String httpResponse = "HTTP/1.1";
httpResponse += " 200 OK \n";
httpResponse += "Content-Type: image/gif\n" ;
httpResponse += "Content-Length: " + f.length()+"\n\n";
serverClient.getOutputStream().write(httpResponse.getBytes("UTF-8"));
//loop to print each line of file to browser
while ((line = bfr.readLine()) != null)
{
serverClient.getOutputStream().write(line.getBytes("UTF-8"));
}
}
else if (extention == "jpg")
{
String line;
String httpResponse = "HTTP/1.1";
httpResponse += " 200 OK \n";
httpResponse += "Content-Type: image/jpg\n" ;
httpResponse += "Content-Length: " + f.length()+"\n\n";
serverClient.getOutputStream().write(httpResponse.getBytes("UTF-8"));
//loop to print each line of file to browser
while ((line = bfr.readLine()) != null)
{
serverClient.getOutputStream().write(line.getBytes("UTF-8"));
}
}
else
{
String line;
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n";
serverClient.getOutputStream().write(httpResponse.getBytes("UTF-8"));
//loop to print each line of file to browser
while ((line = bfr.readLine()) != null)
{
serverClient.getOutputStream().write(line.getBytes("UTF-8"));
}
}
}catch(Exception ex)
{
//when page is loaded, print confirmation to system
System.out.println("999999999");
}
}
您似乎正在用byte-> char-> byte逐行复制为UTF-8字节来处理JPG / GIF文件。相反,您应该将GIF / JPG作为InputStream打开,并且将它们直接写入servlet输出流中而不进行更改。在JPG / GIF块中,您需要替换bfr上的while循环以传递图像而无需进行任何转换:
Files.copy(f.toPath(), serverClient.getOutputStream());
在最后一块,您需要确定哪种字符集适合于要返回的内容。可以按原样使用阅读器,也可以按上述内容以流方式传递,这取决于内容。