File upload using RichFaces

后端 未结 2 934
梦谈多话
梦谈多话 2021-02-06 05:28

I am currently looking in to some file uploading using Java Server Faces. I\'ve found this great introduction to it using RichFaces. However, I have some troubles understanding

2条回答
  •  情深已故
    2021-02-06 06:15

    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:

                                    
    
    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();
    }
    

提交回复
热议问题