I'm searching since one week and couldn't find a proper solution for my problem. So I'm asking the experts here.
I'm trying to implement a page with FileUpload to upload and show the images after upload on same page.
my problem is, if I set my ManagedBean to @RequestScope
, the handleFileUpload
function will not be triggered.
If I set it to @ViewScope
, the function will be triggered but the error "Error in streaming dynamic resource." is shown.
here are my files:
web.xml
<filter> <filter-name>PrimeFaces FileUpload Filter</filter-name> <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class> <init-param> <param-name>thresholdSize</param-name> <param-value>2097152</param-value> </init-param> <init-param> <param-name>uploadDirectory</param-name> <param-value>E:/uploadedImages</param-value> </init-param>
PrimeFaces FileUpload Filter Faces Servlet
Bean
@ManagedBean @RequestScoped public class ImageManager implements Serializable { private final static int MAX_UPLOADED_FILES = 5; private final static String UPLOADED_FILES_PATH = "E:/uploadedImages"; private final Map<UUID, UploadedFile> uploadedFiles = new HashMap<>(); public List<String> getListImages() { final List<String> result = new ArrayList<>(); for (final UUID uuid : uploadedFiles.keySet()) result.add(uuid.toString()); return result; } public StreamedContent getImage() { final ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); final String imageId = (String) externalContext.getRequestMap().get("imageId"); if (imageId != null) { final UUID imageIndex = UUID.fromString(imageId); return new DefaultStreamedContent(new ByteArrayInputStream(uploadedFiles.get(imageIndex).getContents()), "image/jpg"); } return null; } public void handleFileUpload(FileUploadEvent event) { if (uploadedFiles.size() < MAX_UPLOADED_FILES) { final UploadedFile uploadedFile = event.getFile(); if (uploadedFile != null) { uploadedFiles.put(UUID.randomUUID(), uploadedFile); } } } }
xhtml
<p:fileUpload fileUploadListener="#{imageManager.handleFileUpload}" mode="advanced" multiple="true" sizeLimit="2097152" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" uploadLabel="Hochladen" auto="false" cancelLabel="Abbrechen" invalidFileMessage="Die ausgewählte Datei ist kein zugelassene Bilddatei" invalidSizeMessage="Die maximale Bildgröße ist 2MB" label="Datei Auswählen" update="imageList" /> <ui:repeat value="#{imageManager.listImages}" var="imageId" id="imageList"> <h:outputText value="#{imageId}" /> <p:graphicImage value="#{imageManager.image}"> <f:param id="imageId" name="imageId" value="#{imageId}" /> </p:graphicImage> </ui:repeat>