Pergunta

Current situation: in the Java code, I'm fetching documents with attachments from a CouchDB via the Ektorp library. Those documents are mapped into Java objects, all working fine. In order to make those attachments accessible in the browser, I'm instantiating a ByteArrayResource with the document attachment as a byte array, the content-type, and the filename:

private ByteArrayResource handleAttachment(String key, String cType) {
    ByteArrayResource res = null;
    AttachmentInputStream attIS = CouchDB.INSTANCE.getCouchDbConnector().getAttachment(doc.getId(), key);
    InputStream is = new BufferedInputStream(attIS);
    try {
        // Convert InputStream to byte[] with Apache commons-io
        byte[] bytes = IOUtils.toByteArray(is);
        attIS.close();
        is.close();
        res = new ByteArrayResource(cType, bytes, key);
    } catch (IOException e) {
        logger.error("", e);
    }
    return res;
}

I'm then simply adding a ResourceLink to my page:

ByteArrayResource resource = handleAttachment(key, cType);
add(new ResourceLink("resLink", resource));

The problem is: when I'm clicking that link in a browser, all attachments are downloading, no matter what the content-type is. When I access those attachment from the CouchDB directly via the browser, an "image/xxx" content-type opens the image in the browser, "text/xxx" get's displayed in the browser, "and "application/pdf" is also handled by the browser (Safari e.g. displays the PDF immediately).

How can I achieve that with Wicket? Any help is appreciated. Please keep in mind that I do not want shared resources, my site is secured. Thank you!

PS: What's kind of interesting, if I open one of those "image" content-type ResourceLinks with the "rel="prettyPhoto" attribute, I get the JQuery PrettyPhoto plugin to correctly display that picture in a layover. The browser however triggers a download.

Foi útil?

Solução

I see you are using the constructor version of ByteArrayResource which takes in input also the file name (it's the third parameter 'key' in your code). Doing so ByteArrayResource will configure the response as 'ATTACHMENT' and that's why you always get the save dialog. Try to omit key parameter to see if you get the desired behaviour.

Outras dicas

If you want to preserve the filename information you could try overriding method newResourceResponse of ByteArrayResource like this:

res = new ByteArrayResource(cType, bytes, key){
  @Override
  protected AbstractResource.ResourceResponse newResourceResponse(IResource.Attributes attributes){
    AbstractResource.ResourceResponse rr = super.newResourceResponse(attributes)
    rr.setContentDisposition(ContentDisposition.INLINE);
    return rr;
  }
};

In this way you will manually force your response to be INLINE.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top