【问题标题】:Getting an Image properly from My Java Web Server从我的 Java Web 服务器正确获取图像
【发布时间】:2012-05-17 05:48:29
【问题描述】:

我用 Java 创建了一个简单的 HTTP 服务器。当浏览器向我的 Web 服务器发送 GET 请求以获取图像文件时,假设为 .jpg。目前我的浏览器无法正确获取图像。

究竟必须设置哪些标头字段?

目前我有日期、服务器、内容类型、内容长度、连接。我使用以下方法设置长度:

fin = new FileInputStream(fileName);
contentLength = fin.available();

Content-Type 设置为正确的 mime-type,所以没有问题。

我使用以下方式写入文件数据:

public void sendFile (FileInputStream fin, DataOutputStream out) 
{
    byte[] buffer = new byte[1024];
    int bytesRead;
    int strCnt = 0;
    try
    {
        int cnt = 0;
        while ((bytesRead = fin.read(buffer)) != -1)
        {
             out.write(buffer, 0, bytesRead);
        }
        fin.close();
    }
    catch (IOException ex)
    {

    }
}

这是我的 Chrome 浏览器收到的内容

似乎没有下载完整的内容长度。

图片文件的实际大小为2.73KB。

如果没有缺少标题字段,那么可能导致问题的原因是什么?

【问题讨论】:

    标签: java webserver


    【解决方案1】:

    看起来您并未发送所有数据。尝试添加 out.flush(); out.close();在 fin.close() 之前:

    out.flush();
    out.close();
    fin.close();
    

    我还建议您将 DataOutputStream 包装到 BufferedOutputStream 中。根据我的实践,它在写入 hd/network 时比 DataOutputStream 更快。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 2019-06-23
      相关资源
      最近更新 更多