Undertow中的图像/媒体MIME类型响应 [英] Image/Media MIME type responses in Undertow

查看:339
本文介绍了Undertow中的图像/媒体MIME类型响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力寻找在Undertow中传递.jpeg,.png或其他内容的方法。发送byte []将不起作用,因为Undertow是非阻塞的,我不想通过平常来写输出文件:

I've been struggling trying to find a way to deliver .jpeg, .png or other contents in Undertow. Sending byte[] won't work and since Undertow is Non-blocking, I don't want to write the file on the output by doing the usual:

exchange.getOutputStream().write(myFileByteArray);

还有其他方法可以实现吗?我还使用Undertow的默认Base64库在Base64中对图像进行编码,但也没有工作。

Is there any other way I can achieve it? I also encoded the image in Base64 using Undertow's default Base64 library, but didn't work either.

编辑:提供一些代码:
这是我的方法编码文件。它适用于.js,.html和其他文本文件,但不适用于图像。编码工作正常,所以我的问题是,如果我把它发回给请求的人时做错了。

providing some code: This is my method that encodes a file. It works for .js, .html and other text files, but not for images. The encoding is working, though, so my question is if I'm doing something wrong when sending it back to the person who requested.

这是我如何回应: (硬编码用于stackoverflow目的)

This how I'm responding: (hardcoded for stackoverflow purposes)

exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "image/jpeg");
exchange.getResponseSender().send(getResource(resource, true));

我没有在下方获得任何例外。图片不会出现在浏览器上。浏览器说它无法解码图像..

谢谢。

推荐答案

好的,所以经过大量的工作,想知道我的MIME配置是否正确,我实际上发现你只需要将文件写入交换对象的OutputStream。

Ok, so after a lot of work wondering if my MIME configuration was right, I actually found out that you only need to write the file to the OutputStream of the exchange object.

这是我做的:

if(!needsBuffering){
    exchange.getResponseSender().send(getResource(resource));
}else{
    exchange.startBlocking();
    writeToOutputStream(resource, exchange.getOutputStream());
}

...

private void writeToOutputStream(String resource, OutputStream oos) throws Exception {

    File f = new File(this.definePathToPublicResources() + resource);

    byte[] buf = new byte[8192];

    InputStream is = new FileInputStream(f);

    int c = 0;

    while ((c = is.read(buf, 0, buf.length)) > 0) {
        oos.write(buf, 0, c);
        oos.flush();
    }

    oos.close();
    is.close();

}

这篇关于Undertow中的图像/媒体MIME类型响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆