2

I have a table with blob content in it, in which I store different file types(text, audio, image, etc). After retrieving the byte [] successfully, I don't have any idea of how to convert the [] in such a way as to convert it into a download dialog box.
Here is my code

trns = session.beginTransaction();
Query query = session.createQuery("from FileDownload as fu where fu.Id =:Id");
query.setInteger("Id", id);
FileDownload fileDownload = (FileDownload) query.iterate().next();
byte[] byteArray = fileDownload.getFile();

The above code works fine and I receive a byte []. But I don't know how to proceed further in order to convert it into a file with the dialog appearing.

Can anyone please help me?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Freakyuser
  • 2,774
  • 17
  • 45
  • 72

2 Answers2

11

Assuming you know the mimeType and filename of your file, you can set the content type and the HTTP header Content-Disposition.

Just write the byte array to the OutputStream:

    // The response from your servlet.
    HttpServletResponse resp;
    resp.setContentType(mimeType);
    resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
    resp.getOutputStream().write(byteArray);
Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
  • Thank you for the answer. About the `mimeType`, can we get it without the file name? – Freakyuser Dec 21 '12 at 12:11
  • 1
    you can use mimeType or the Content-Disposition header alone. But to find out the mimeType of the file is very difficult without the file name (and keep in mind, that the file name is not necessarily accurate, as well). -- Typically, you "guess" the mimeType based on the file name suffix (JPG, WAV, MP3 etc.) and store it alongside with the file data. – Moritz Petersen Dec 21 '12 at 12:13
  • 2
    No, one doesn't "guess" the MIME type. If you only look at the file name that it's indeed a guessing game. Instead you need to check the magic bytes i.e. the first few bytes of a file. It's not complicated but just tedious. https://sourceforge.net/projects/jmimemagic/ or https://sourceforge.net/projects/mime-util/ do just that. – Marcel Stör Dec 21 '12 at 12:47
1

The byte array can be sent to the client from a servlet. You can find many discussions on the topic here and elsewhere.

Here are folks discussing efficiency of streaming (with code). Here is a discussion on how to map the servlet to a url (with examples).

The last thing for you to do is just link the user to the servlet's URL when they click the button.

You'll also want to look into what additional info you can provide in the header before streaming the byte array. For example, if you provide a mime type the browser then has a clue what to do with the file; open PDFs in the browser, display images in the browser; open xls files in Excel.

Community
  • 1
  • 1
Sean Connolly
  • 5,692
  • 7
  • 37
  • 74