Wrong decoding on downloaded file

I’m trying to implement a simple download functionality in a Vaadin application to retrieve a file from an Oracle database and to send it to the client for download.

The simplest solution I’ve found to this is (this code is the method fired by a ClickButton event):

String fileName = attachment.getFileName();
String mimeType = attachment.getContentType();
BlobT blobT = (BlobT) attachment.getBlobs().toArray()[0]
;

final byte[] fileContent = blobT.getAttachmentBlob();

StreamSource ss = new StreamSource() {
    byte[] bytes = fileContent;
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);

    @Override
    public InputStream getStream() {
        return is;
    }
};

StreamResource sr = new StreamResource(ss, fileName, ApplicationHelper.getCurrentApplication());
sr.setMIMEType(mimeType);
ApplicationHelper.getCurrentApplication().getMainWindow().open(sr, "_top");

The problem is that the downloaded file appears to be badly decoded: a simple txt with the phrase

becomes

I also tried this solution but the result is the same:

final FileResource stream = new FileResource(new File(""), ApplicationHelper.getCurrentApplication()) {
    @Override
    public DownloadStream getStream() {
        ByteArrayInputStream in = new ByteArrayInputStream(fileContent);
        DownloadStream ds = new DownloadStream(in, contentType, fileName);
        ds.setParameter("Content-Disposition", "attachment; filename=" +fileName);
        return ds;
    }
};
stream.setCacheTime(0);
ApplicationHelper.getCurrentApplication().getMainWindow().open(stream, "_top");

I can assure you that the file is stored successfully on the database. If I try to open the blob from SQL Developer, I can see that the file is not corrupted. I’ve already checked the MIME type stored, and it is the correct one: i.e. “text/plain” for .txt files, “application/pdf” for .pdf files.

Thank you in advance.
Dolfiz

Found a solution!

The problem lied on a mapping issue: the BLOB column on database was mapped correctly as a
byte[]

but it seems that, for proper managing the BLOB type, the annotation
@Lob
from
javax.persistence
is needed.

Here’s the correct column mapping:

@Column(name = "ATTACHMENT")
@Lob
private byte[] attachmentBlob;

Hope this could help someone :wink:
Bye!
Luca