Ответ 1
В методе действий вы можете получить ответ сервлета HTTP из-под контуров JSF ExternalContext#getResponse()
. Затем вам нужно установить как минимум заголовок HTTP Content-Type
на application/pdf
и заголовок HTTP Content-Disposition
на attachment
(если вы хотите открыть диалог Сохранить как) или inline
(если вы хотите, чтобы webbrowser обрабатывает сам дисплей). Наконец, вам нужно убедиться, что вы вызываете FacesContext#responseComplete()
, чтобы избежать IllegalStateException
.
Пример Kickoff:
public void download() throws IOException {
// Prepare.
byte[] pdfData = getItSomehow();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
// Initialize response.
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType("application/pdf"); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setHeader("Content-disposition", "attachment; filename=\"name.pdf\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead.
// Write file to response.
OutputStream output = response.getOutputStream();
output.write(pdfData);
output.close();
// Inform JSF to not take the response in hands.
facesContext.responseComplete(); // Important! Else JSF will attempt to render the response which obviously will fail since it already written with a file and closed.
}
Тем не менее, если у вас есть возможность получить содержимое PDF как InputStream
, а не byte[]
, я бы рекомендовал использовать это вместо этого, чтобы сохранить webapp из памяти hogs. Затем вы просто пишете его в известном цикле InputStream
- OutputStream
обычным способом Java IO.