@Test public void getImageInRenderPhase() throws IOException { mediaBean.setRequestParameter("email"); mediaBean.setRenderPhase(true); StreamedContent streamedContent = mediaBean.getImage(); Assert.assertNotNull(streamedContent); Assert.assertNull(streamedContent.getStream()); }
@Test public void getImage() throws IOException { mediaBean.setRequestParameter("email"); StreamedContent streamedContent = mediaBean.getImage(); Assert.assertNotNull(streamedContent); Assert.assertNotNull(streamedContent.getStream()); Assert.assertEquals("png", streamedContent.getContentType()); Assert.assertEquals("email", streamedContent.getName()); }
/** * Crea un archivo para que pueda ser descargado en el navegador, debe previamente existir el path * de archivo * * @param path */ public void crearArchivo(String path) { FacesContext facesContext = FacesContext.getCurrentInstance(); StreamedContent content; InputStream stream = null; try { if (path.startsWith("/")) { stream = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()) .getResourceAsStream(path); } else { stream = new FileInputStream(path); } } catch (Exception e) { crearError("No se puede generar el archivo path: " + path, "crearArchivo()", e); } if (stream == null) { return; } content = new DefaultStreamedContent(stream); if (content == null) { return; } ExternalContext externalContext = facesContext.getExternalContext(); String contentDispositionValue = "attachment"; try { externalContext.setResponseContentType(content.getContentType()); externalContext.setResponseHeader( "Content-Disposition", contentDispositionValue + ";filename=\"" + path.substring(path.lastIndexOf("/") + 1) + "\""); externalContext.addResponseCookie( Constants.DOWNLOAD_COOKIE, "true", new HashMap<String, Object>()); byte[] buffer = new byte[2048]; int length; InputStream inputStream = content.getStream(); OutputStream outputStream = externalContext.getResponseOutputStream(); while ((length = (inputStream.read(buffer))) != -1) { outputStream.write(buffer, 0, length); } externalContext.setResponseStatus(200); externalContext.responseFlushBuffer(); content.getStream().close(); facesContext.getApplication().getStateManager().saveView(facesContext); facesContext.responseComplete(); } catch (Exception e) { crearError("No se puede descargar : path: " + path, "crearArchivo()", e); } }
public void uploadFoto(FileUploadEvent event) { FacesMessage msg = new FacesMessage("Sucesso!!"); FacesContext.getCurrentInstance().addMessage(null, msg); try { imagem = new DefaultStreamedContent( event.getFile().getInputstream(), "image/jpeg", event.getFile().getFileName()); ControllerArquivo.guardarArquivo( imagem.getStream(), "imagens\\temp\\categoria\\", "fotoPerfil.jpg"); } catch (IOException e) { e.printStackTrace(); } }