【问题标题】:How do I display a html file with an image, from a servlet?如何从 servlet 显示带有图像的 html 文件?
【发布时间】:2015-09-16 17:19:36
【问题描述】:

我想从我的 servlet 显示一个 html 文件,该 html 文件存储在与我的 webapp 不同的服务器中,我目前正在使用 FileInputStream 和 ServletOutputStream 类使其工作,问题是它没有显示图像。 这是我的 servlet 的代码:

public class DisplayImage extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    response.setContentType("text/html");
    ServletOutputStream out;
    out = response.getOutputStream();
    FileInputStream fin = new FileInputStream("C:\\Sistemas\\tendBe.html");

    BufferedInputStream bin = new BufferedInputStream(fin);
    BufferedOutputStream bout = new BufferedOutputStream(out);
    int ch = 0;;
    while ((ch = bin.read()) != -1) {
        bout.write(ch);
    }

    bin.close();
    fin.close();
    bout.close();
    out.close();       

//This doesn't work, it doesn't take that path.
   // RequestDispatcher view = request.getRequestDispatcher("file://C://Sistemas//tendBe.html");

    //view.forward(request, response);

}}

这是我的 html 文件:

<html>
    <head>
    <title>Grafico</title>
    </head>
    <body>

       <h2 style='background-color:Lightgray;'><center>Tendencia    Beetle</center>       </h2>
       <div align='center'><b>Fecha: 25/06/2015<br>
       Status: 21:25</b></div>
       <center><b> 75</b></div><center>
       <br>
       <Left><img src='tendBe.png'><Left>
       <Left><img src='file:\\C:\\Sistemas\\tendBe.png'><Left>
    </body>
</html>

结果,它确实显示了 html 页面,但不知何故,图像丢失了。我认为这可能是因为我在其中指定文本并且还发送图像的 setContentType? 你有什么建议吗? 此外,使用 getRequestDispatcher 的部分给我带来了麻烦,因为它不接受特定路径,而且我认为我不会将文件放在应用程序文件夹中。感谢您的帮助。

【问题讨论】:

    标签: java html jsp servlets


    【解决方案1】:

    问题是因为您的网络应用文件夹中没有这些文件。生成的 html 仍然指向服务器上位置 file:\\C:\\Sistemas\\tendBe.png 的图像,客户端肯定无法访问。

    到目前为止,我的建议是创建另一个 servlet 来读取图像,就像您为 html 所做的那样。同时将html中的图片src更新为新的图片servlet url。

    或者您可以将图像转换为base64字符串data url并将其用作html页面中的图像src。通过这种方式,您可以跳过创建新图像 servlet 的需要。有几个在线工具可以转换图片like

    Using data url
    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
    9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

    【讨论】:

    • 谢谢!你是对的,我的 html 仍然指向一个本地地址,我将它更改为服务器的地址,它现在可以工作了。我不需要更改任何其他内容。
    【解决方案2】:

    您必须更改 HTML 中 img 标记的 src 属性,以提供正确的图像 URL。而且您必须找到一种从服务器提供这些图像的方法。

    提示:图像(通常)由单独的请求提供,即浏览器发出请求以获取 HTML,然后分析 HTML,如果找到需要下载的元素(例如图像或 CSS/ Javascript 文件),浏览器发出一个新请求来获取它们(每个元素一个请求)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 2013-01-11
      • 2021-02-13
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多