File upload using RichFaces

偶尔善良 提交于 2019-12-03 03:09:17

Writing things to your WAR directory (assuming the WAR is even exploded as a directory) is, in generally, a bad idea (for the same reasons that storing your data in your application directory is usually a bad idea).

You'd probably want it to end up in a persistence store, usually a database. Exactly how you manage that is up to you - whether you use the file system and store a reference in the database or store a BLOB in the database directly and whether you use JDBC or JPA or Hibernate, etc.

The list of uploaded files could then be read from the database by refreshing the panel that contained them using something like <a4j:support event="onuploadcomplete" reRender="info" />.

A file download servlet (if RichFaces doesn't have one) is fairly easy to write.

Not sure how much help this is (and probably way too late!), but this is the code I use on the server side, equivalent to your listener.

public String uploadFile(UploadEvent event) {
    UploadItem item = event.getUploadItem();

    String name = "unnamed_attachment";
    byte[] data = item.getData();

    try {
        name = FilenameUtils.getName(item.getFileName());
        data = FileUtils.readFileToByteArray(item.getFile());
        logger.info("data.length = " + data.length);
        UploadDetails details = new UploadDetails(); // This is a javabean that gets persisted to database (actually a ejb3 entity bean, but thats irrelevant)

        details.setBytes(data);
        details.setResume(true);
        // Save to database here 

    } catch (Exception e) {
        FaceletsUtil.addSystemErrorMessage();
        logger.error(e, e);
    }
    return null;
}

The big question remaining is you say "how would you make the file available to the webbapplication?". The byte array is available immediately. If you want to re-download the file, you can provide it as a link to a method in a JSF session/view bean like:

<h:commandButton action="#{Manager.downloadFile}" value="Download report">                                </h:commandButton>

public void downloadFile() {
    final HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();

    response.setHeader("Content-Disposition", "attachment;filename=radar-report" + new Date() + ".pdf"); // or whatever type you're sending back
    try {
        response.getOutputStream().write(uploadDetails.getBytes()); // from the UploadDetails bean
        response.setContentLength(uploadDetails.getBytes().length);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (IOException e) {
        logger.error(e, e);  
    }
    FacesContext.getCurrentInstance().responseComplete();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!