Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JSF1.2添加一个输入文件_Jsf_File Upload_Richfaces_Jsf 1.2 - Fatal编程技术网

使用JSF1.2添加一个输入文件

使用JSF1.2添加一个输入文件,jsf,file-upload,richfaces,jsf-1.2,Jsf,File Upload,Richfaces,Jsf 1.2,我需要上传一个专门用于上传文件的表单。在我的项目中,我可以使用JSF1.2和RichFaces 3.3.3,但我不能使用,因为我的客户需要一个简单的输入,就像一样 如果可以,我会使用Primeface或Tomahawk的文件上载,但我是被禁止的,我不能使用其他库,我也不能使用Servlet 3.0 nether Apache文件上载。我现在能做什么?我见过其他类似的问题,但他们可以使用其他lib,我就是不能,我受到限制…我已经有一段时间没有为JSF编写MIME解析器了,但我记得这个过程就是这样的

我需要上传一个专门用于上传文件的表单。在我的项目中,我可以使用JSF1.2和RichFaces 3.3.3,但我不能使用
,因为我的客户需要一个简单的输入,就像
一样

如果可以,我会使用Primeface或Tomahawk的文件上载,但我是被禁止的,我不能使用其他库,我也不能使用Servlet 3.0 nether Apache文件上载。我现在能做什么?我见过其他类似的问题,但他们可以使用其他lib,我就是不能,我受到限制…

我已经有一段时间没有为JSF编写MIME解析器了,但我记得这个过程就是这样的

您需要编写一个解析器来从
多部分/formdata
负载中提取数据。有一个很好的例子

您需要决定是否针对以下目标:

  • 具有普通表单/控件的非JSF servlet
  • 带有JSF表单和自定义文件上载控件的JSFServlet
以普通servlet为目标

只要upload POST操作不需要调用依赖于JSF上下文(托管bean等)的代码,这将是一种更简单的方法

您的servlet解析来自输入流的数据,并根据需要对其进行操作

针对JSF视图/操作

在这里,您需要对请求进行修饰(理想情况下使用a),以向JSF框架提供解析后的请求。这通常在从HTTP头检测post类型的服务器中完成。在调用任何表单操作之前,需要决定文件数据存储在何处,以及如何将该数据公开给托管bean

您还需要考虑是否要为文件上传输入类型创建自定义JSF控件,或者是否可以用普通HTML元素进行脱除。


值得检查解析器/控件的功能,您不能使用这些功能来确保提供简单的功能,例如最大负载大小,以防止攻击者将千兆字节的数据上传到您的应用程序。

为了用可接受的解决方案解决此问题,我创建了一个普通表单和一个servlet,servlet接收
多部分/表单数据
请求,并使用RichFaces 3.3.3中包含的解析接收到的参数和附加文件,然后我将
文件
实例保存在会话中,并将其恢复到JSF上下文中

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>
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;


}

我以前也遇到过同样的问题。我通过在用户点击浏览按钮时打开一个弹出窗口解决了这个问题,这个新弹出窗口直接链接到一个支持文件上传和下载的servlet。 一旦上传了一个文件,servlet调用window.close()将在加载servlet主体时直接关闭弹出窗口。 以下是所做的更改:

在addItem.jsp中,提示用户输入文件:

<script type="text/javascript">
       ...
  function newWindow()
  {
    popupWindow = window.open('addItemImage.jsp','name','width=200,height=200');
  }
    ...
 </script>

     <f:view>
         <h:form id="search" onsubmit="return validateDetails()">
          ...

           <h:panelGroup>
                <font color="black">Item Image :</font>
           </h:panelGroup>
           <h:panelGroup>
                <input type="button" value="Upload Image" onClick="newWindow()"/>
           </h:panelGroup>

          ...
          </h:form>
      </f:view>

...
函数newWindow()
{
popupWindow=window.open('addItemImage.jsp','name','width=200,height=200');
}
...
...
项目图像:
...
在打开的新弹出窗口中:addItemImage.jsp

<script type="text/javascript">
    function validate()
    {
        var file = document.getElementById("file").value;
        if(file == null || file == "")
            return true;
        if(file.indexOf(".jpg") == -1 && file.indexOf(".gif")  && file.indexOf(".bmp") == -1 && file.indexOf(".jpeg") == -1) 
        {
            alert("Invalid File Format!! Please upload jpg/bmp/gif");
            return false;
        }
        return true;
    } 
</script>
<body>
    <form enctype="multipart/form-data" method="post" action="FileUploaderServler.view" onsubmit="return validate()">
        <input type="file" name="file" id="file" />
        <input type="submit" value="Upload Image">
    </form>
</body>

函数验证()
{
var file=document.getElementById(“文件”).value;
如果(文件==null | |文件==“”)
返回true;
if(file.indexOf(“.jpg”)=-1&&file.indexOf(“.gif”)&&file.indexOf(“.bmp”)=-1&&file.indexOf(“.jpeg”)=-1)
{
警告(“文件格式无效!!请上传jpg/bmp/gif”);
返回false;
}
返回true;
} 
这将发布到一个servlet,然后该servlet将呈现图像并将其保存在一个地方。 FileUploaderServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        List<FileItem> items = null;
        try 
        {
             MultipartHTTPServletRequest multipartHTTPServletRequest = new MultipartHTTPServletRequest(Connection.getRequest());
            items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartHTTPServletRequest);
        } 
        catch (FileUploadException e) 
        {
            e.printStackTrace();
        }
        if(!Util.isNullList(items))
        {
            for (FileItem item : items) 
            {
                if (!item.isFormField()) 
                {
                    String itemName = item.getFieldName();
                    InputStream filecontent = null;

                    try 
                    {
                        filecontent = item.getInputStream();
                    } 
                    catch (IOException e) 
                    {
                        e.printStackTrace();
                    }

                   /* String currDirPath = System.getProperty("user.dir"); // C:\Users\KISHORE\Desktop\eclipse
                    File file = new File(currDirPath+"\\itemImages");*/
                    new File(Constants.ABS_FILE_PATH_TO_IMAGES).mkdir();
                    File fw = new File(Constants.ABS_FILE_PATH_TO_IMAGES+"\\"+Connection.getRequest().getSession().getId()+".jpg"); // E:\Kishore Shopping Cart\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ShoppingCart\WEB-INF\itemImages\EC34EEE58065AD674192D3D57124F07E.jpg
                    fw.delete();
                    fw.createNewFile();
                    try 
                    {
                        item.write(fw);
                    } 
                    catch (Exception e) 
                    {
                        e.printStackTrace();
                    }
                }
            }

        }

        PrintWriter out = response.getWriter();
        out.print("<html><title>Add Image to Item</title><body onload='window.close()'>Uploaded Successfully!!</body>");
        System.out.print("</html>");
    }
protectedvoiddopost(HttpServletRequest请求,HttpServletResponse响应)抛出ServletException,IOException
{
列表项=空;
尝试
{
MultipartTTpServletRequest MultipartTTpServletRequest=新的MultipartTTpServletRequest(Connection.getRequest());
items=new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartHTTPServletRequest);
} 
捕获(文件上载异常)
{
e、 printStackTrace();
}
如果(!Util.isNullList(项目))
{
用于(文件项:项)
{
如果(!item.isFormField())
{
字符串itemName=item.getFieldName();
InputStream filecontent=null;
尝试
{
filecontent=item.getInputStream();
} 
捕获(IOE异常)
{
e、 printStackTrace();
}
/*字符串currDirPath=System.getProperty(“user.dir”);//C:\Users\KISHORE\Desktop\eclipse
文件文件=新文件(currDirPath+“\\itemImages”)*/
新文件(Constants.ABS_File_PATH_TO_IMAGES).mkdir();
File fw=new File(Constants.ABS\u File\u PATH\u TO\u IMAGES+“\\”+Connection.getRequest().getSession().getId()+“.jpg”);/E:\Kishore Shopping Cart\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ShoppingCart\WEB-INF\itemmages\ec34ee58065ad674192d57124f07e.jpg
fw.delete();
createNewFile();
尝试
{
项目.编写(fw);
} 
捕获(例外e)
{
e、 printStackTrace();
}
}
}
}
PrintWriter out=response.getWriter();
打印(“将图像添加到已成功上载的项目!!”;
系统输出打印(“”);
}
在plac上完成文件保存后,此servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        List<FileItem> items = null;
        try 
        {
             MultipartHTTPServletRequest multipartHTTPServletRequest = new MultipartHTTPServletRequest(Connection.getRequest());
            items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartHTTPServletRequest);
        } 
        catch (FileUploadException e) 
        {
            e.printStackTrace();
        }
        if(!Util.isNullList(items))
        {
            for (FileItem item : items) 
            {
                if (!item.isFormField()) 
                {
                    String itemName = item.getFieldName();
                    InputStream filecontent = null;

                    try 
                    {
                        filecontent = item.getInputStream();
                    } 
                    catch (IOException e) 
                    {
                        e.printStackTrace();
                    }

                   /* String currDirPath = System.getProperty("user.dir"); // C:\Users\KISHORE\Desktop\eclipse
                    File file = new File(currDirPath+"\\itemImages");*/
                    new File(Constants.ABS_FILE_PATH_TO_IMAGES).mkdir();
                    File fw = new File(Constants.ABS_FILE_PATH_TO_IMAGES+"\\"+Connection.getRequest().getSession().getId()+".jpg"); // E:\Kishore Shopping Cart\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ShoppingCart\WEB-INF\itemImages\EC34EEE58065AD674192D3D57124F07E.jpg
                    fw.delete();
                    fw.createNewFile();
                    try 
                    {
                        item.write(fw);
                    } 
                    catch (Exception e) 
                    {
                        e.printStackTrace();
                    }
                }
            }

        }

        PrintWriter out = response.getWriter();
        out.print("<html><title>Add Image to Item</title><body onload='window.close()'>Uploaded Successfully!!</body>");
        System.out.print("</html>");
    }