Search code examples
jsffile-uploadrichfacesjsf-1.2

Add a input file with JSF 1.2


I need to upload in a form dedicated to upload files. In my project I can use JSF 1.2 and RichFaces 3.3.3 but I can't use the <rich:fileUpload/> because my client wants a simple input, just like <input type="file"/>.

If I could I would use Primeface's or Tomahawk's file upload, but I'm forbidden, I can't use other libraries, I also can't use Servlet 3.0 nether Apache fileupload. What can I do now? I've seen other similar questions, but they could use other libs, I just can't, I'm restricted...


Solution

  • To solve this issue with an acceptable solution I created a normal form and a servlet, the servlet receives the multipart/form-data request and uses the org.ajax4jsf.request.MultipartRequest included in RichFaces 3.3.3 to parse the received parameters and the attached file, then I save the File instance in a session and I restore it inside the JSF context.

    xhtml:

    <a4j:form >
        <a4j:jsFunction name="finishUpload" 
                action="#{importacaoController.actionUploadArquivoDadosXX}"
                reRender="uploadedFile,globalMensagens" />
        <a4j:jsFunction
            name="tipoNaoSuportado" reRender="globalMensagens" action="#{importacaoController.actionTipoNaoSuportado }"
            />
    </a4j:form>
    <form target="uploader" id="uploaderForm" action="#{request.contextPath}/MyServlet"
        method="post" enctype="multipart/form-data" style="position: absolute;margin: -210px 0 0 300px;">
        <div class="modulo-6-12">
            <label for="uploadFileField">Anexar arquivo</label><br/>
            <input type="file" id="uploadFileField" name="upload" onchange="jQuery('#uploaderForm').submit();" />
        <br />
        <small><h:outputText id="uploadedFile" value="#{importacaoController.arquivoConfig.name}" /></small>
        </div>
    </form>
    <iframe id="uploader" width="0" height="0" src="" style="display: none; border: 0; margin:0;padding:0;"></iframe>
    

    Servlet:

    public class MyServlet extends HttpServlet {
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String encoding = request.getCharacterEncoding();
            if(encoding == null) request.setCharacterEncoding("UTF-8");
            MultipartRequest mpRequest = new MultipartRequest(request,true,10*1024*1024,"importarXX");
            String field = "upload";
            Object o =mpRequest.getFile(field);
            if(o instanceof File)
            {
                File file = (File)o;
                HttpSession sess = request.getSession();
                String name = mpRequest.getFileName(field);
    
                Writer w = response.getWriter();
                w.write("<html><head><script>");
                if(!name.endsWith(".xls"))
                {
    
                    w.write("parent.window.tipoNaoSuportado()" +
                            //"alert('Só são permitidos arquivos com extensão .xls');" +
                            "</script></head><body></body></html>");
                    w.close();
                    file.delete();
                    return;
                }
    
                sess.setAttribute("importarXXFile", o);
                sess.setAttribute("importarXXFileName", name);
                w.write("parent.window.finishUpload();</script></head><body>Sucesso</body></html>");
                w.close();
            }
        }
    }
    

    Controller:

    public boolean actionUploadArquivoDadosXX(){
        flgTipoNaoSuportado = false;
        HttpSession sess = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getSession();
        File uploadedFile = (File) sess.getAttribute("importarXXFile");
        String uploadedFileName = (String) sess.getAttribute("importarXXFileName");
        boolean ret = false;
    
        if(uploadedFile != null && uploadedFileName != null){
            BeanArquivoUpload arquivo = new BeanArquivoUpload();
            arquivo.setFile(uploadedFile);
            arquivo.setName(uploadedFileName);
            arquivo.setFileSize(uploadedFile.length());
            setArquivoConfig(arquivo);
            ret = true;
        }
        else
        {
             setArquivoConfig(null);
        }
    
        sess.removeAttribute("importarXXFile");
        sess.removeAttribute("importarXXFileName");
    
        return ret;
    
    
    }