Image/Media MIME type responses in Undertow

痞子三分冷 提交于 2019-12-08 02:51:49

问题


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);

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.

Edit: 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.

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

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

I'm not getting any exception on the undertow side. Image just won't show up on the browser. The browser says it can't decode the image..

Thanks.


回答1:


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.

Here's what I did:

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();

}


来源:https://stackoverflow.com/questions/29023144/image-media-mime-type-responses-in-undertow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!