我从一周开始就在搜索,但找不到适合我的问题的解决方案。所以我在这里问专家。
我正在尝试使用 FileUpload 实现一个页面来上传并在同一页面上上传后显示图像。
我的问题是,如果我将 ManagedBean 设置为@RequestScope
,handleFileUpload
则不会触发该功能。如果我将其设置为@ViewScope
,该功能将被触发,但错误“流式动态资源中的错误”。显示。
这是我的文件:
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
豆
@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>