簡體   English   中英

如何通過 Java Web 服務器在瀏覽器中顯示圖像/gif

[英]How to display an image/gif in a browser through a Java Web Server

我有一個簡單的 Java Web 服務器,我試圖用它在瀏覽器中顯示圖像。

到目前為止,我有它,所以當去 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");
      }

    }

通過使用 BufferedReader,您將損壞 JPG/GIF 文件,因為這會逐行將一系列字節 -> 轉換為 char -> UTF-8 字節。 相反,您應該將 GIF/JPG 作為 InputStream 打開,並將它們直接寫入 servlet output stream 不變。 擺脫這些循環:

//loop to print each line of file to browser
while ((line = bfr.readLine()) != null) 
{
   serverClient.getOutputStream().write(line.getBytes("UTF-8"));
}

只需使用 NIO Files 直接復制圖像,無需任何轉換:

Files.copy(f.toPath(), serverClient.getOutputStream());

bfr 上的第三個也是最后一個循環可能會或可能不會工作,具體取決於文件所代表的內容。 您的文件可能是基於字符的(例如 TXT)文件,因此一次寫入一行調用 BufferedReader readLine 將起作用,如果您在 HTTP servlet 響應上設置字符集,這將很有幫助。 如果文件是二進制格式,例如 MP3 等,那么您的第三個循環只會破壞 stream 就像 GIF/JPG 一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM