user2504767
user2504767

Reputation:

How to create a specific file with an InputStream in Java?

I have storaged in file in my database (format byte[]) and the name and format of the file.

Now i convert my bytearray into an InputStream. How can i recreated the specific file with this InputStream, which was saved in the database before? For example, a PDF document must be a PDF document and a txt file muste be a txt file.

I work with jsf and this is my current code:

Dto currentDto = //code to get the file from the database

final FacesContext facesContext = FacesContext.getCurrentInstance();
final ExternalContext externalContext = facesContext.getExternalContext();
final HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

InputStream inputStream = new ByteArrayInputStream(currentDto.getFileBytes());
OutputStream outputStream = response.getOutputStream();

Upvotes: 0

Views: 2856

Answers (1)

BalusC
BalusC

Reputation: 1109272

Set the Content-Type header in the response. During saving the file in the DB, you should have determined the file's content type or at least the original file extension.

Imagine that you have obtained the file name of the uploaded file as follows, using Apache Commons IO:

String filename = FilenameUtils.getName(uploadedFile.getName());

Then you could determine the content type as follows:

ServletContext servletContext = (ServletContext) externalContext.getContext();
String contentType = servletContext.getMimeType(filename);

Save it along the file content in the DB so that you can upon retrieval do:

byte[] content = currentDto.getFileBytes(); // Terrible classname, by the way.
String contentType = currentDto.getFileContentType();

Finally send it to the HTTP response as follows (no need for massaging it into InputStream):

response.setContentType(contentType);
response.setContentLength(content.length);
response.setHeader("Content-Disposition", "attachment");
response.getOutputStream().write(content);

Alternatively, save the filename instead of the content type in the DB and do the ServletContext#getMimeType() during streaming the file download only:

response.setContentType(servletContext.getMimeType(filename));

The filename is namely also useful for Content-Disposition header, the sane webbrowser (read: everything but MSIE, it uses the last path in request URL instead) will use it as Save As filename.

response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

See also:

Upvotes: 1

Related Questions