Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何通过JavaHTTP服务器发送图像_Java_Http - Fatal编程技术网

如何通过JavaHTTP服务器发送图像

如何通过JavaHTTP服务器发送图像,java,http,Java,Http,我正在使用HttpServer和HttpHandler开发一个HTTP服务器 服务器应使用XML数据或图像响应客户端 到目前为止,我已经开发了HttpHandler实现,可以用XML数据响应客户端,但我无法实现HttpHandler从文件读取图像并将其发送到客户端(例如浏览器) 图像不应该完全加载到内存中,所以我需要某种流式解决方案 public class ImagesHandler implements HttpHandler { @Override public void

我正在使用
HttpServer
HttpHandler
开发一个HTTP服务器

服务器应使用XML数据或图像响应客户端

到目前为止,我已经开发了
HttpHandler
实现,可以用XML数据响应客户端,但我无法实现
HttpHandler
从文件读取图像并将其发送到客户端(例如浏览器)

图像不应该完全加载到内存中,所以我需要某种流式解决方案

public class ImagesHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange arg0) throws IOException {
        File file=new File("/root/images/test.gif");
        BufferedImage bufferedImage=ImageIO.read(file);

        WritableRaster writableRaster=bufferedImage.getRaster();
        DataBufferByte data=(DataBufferByte) writableRaster.getDataBuffer();

        arg0.sendResponseHeaders(200, data.getData().length);
        OutputStream outputStream=arg0.getResponseBody();
        outputStream.write(data.getData());
        outputStream.close();
    }
}

此代码只向浏览器发送512字节的数据。

DataBufferByte
将其数据存储在银行中
getData()
只检索第一个银行,因此您只声明第一个银行的长度,然后只写入第一个银行

请尝试以下方法(未测试),而不是当前的写入行:


您在这里做的工作太多了:解码图像并将其存储在内存中。您不应该尝试将文件作为图像读取。那没用。浏览器需要的只是图像文件中的字节。因此,您只需按原样发送图像文件中的字节:

File file = new File("/root/images/test.gif");
arg0.sendResponseHeaders(200, file.length());
// TODO set the Content-Type header to image/gif 

OutputStream outputStream=arg0.getResponseBody();
Files.copy(file.toPath(), outputStream);
outputStream.close();

这样,图像就可以在浏览器上下载。如果我需要在浏览器中显示图像(有点像有标签),该怎么办?@HarshChiki
File file = new File("/root/images/test.gif");
arg0.sendResponseHeaders(200, file.length());
// TODO set the Content-Type header to image/gif 

OutputStream outputStream=arg0.getResponseBody();
Files.copy(file.toPath(), outputStream);
outputStream.close();