JSF文件上传功能

 

          最近项目需要用jsf1.2实现文件上传功能,我没有采用myfaces,而是用Apache MyFaces Trinidad 这个实现的文件上传,实现方法和myfaces是一样的。页面采用的是.xhtml。

    Apache MyFaces Trinidad是一个基于部分Oracle's ADF Faces构建的JSF1.2组件库。我们要先下在它的jar包,然后导入到我们工程里面。http://myfaces.apache.org/trinidad/index.html这个链接里有文档和包的下载。

    下面来看看代码,首先要配置web.xml文件,配置文件里的UPLOAD_MAX_MEMORY设置成500k说明只要是小于500k的文件都会存放在memory里面,UPLOAD_MAX_DISK_SPACE设置成5000k说明上传文件最大为5000k,并且大小在500k和5000k之间的文件才会存放在磁盘默认路径里面,UPLOAD_TEMP_DIR用来设置存放文件的路径

<? xml version="1.0" encoding="UTF-8" ?>
< web-app  xmlns ="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"  version ="2.5"
    xsi:schemaLocation
="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" >
    
< context-param >
    
<!--  Maximum memory per request (in bytes)  -->
    
< param-name > org.apache.myfaces.trinidad.UPLOAD_MAX_MEMORY </ param-name >
    
<!--  Use 500K  -->
    
< param-value > 512000 </ param-value >
  
</ context-param >
  
< context-param >
    
<!--  Maximum disk space per request (in bytes)  -->
    
< param-name > org.apache.myfaces.trinidad.UPLOAD_MAX_DISK_SPACE </ param-name >
    
<!--  Use 5,000K  -->
    
< param-value > 5120000 </ param-value >
  
</ context-param >
  
< context-param >
    
<!--  directory to store temporary files  -->
    
< param-name > org.apache.myfaces.trinidad.UPLOAD_TEMP_DIR </ param-name >
    
<!--  Use a TrinidadUploads subdirectory of /tmp  -->
    
< param-value > /tmp/TrinidadUploads/ </ param-value >
  
</ context-param >

  
<!--  This filter is always required;  one of its functions is 
          file upload. 
-->
  
< filter >
    
< filter-name > trinidad </ filter-name >
    
< filter-class > org.apache.myfaces.trinidad.webapp.TrinidadFilter </ filter-class >
  
</ filter >

</ web-app >

 

然后是faces-config.xml的配置信息

 

<? xml version='1.0' encoding='UTF-8' ?>

< faces-config  xmlns ="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
    version
="1.2" >

    
<!--   upload files by lw  -->
    
< navigation-rule >
        
< from-view-id > /upload/upload.xhtml </ from-view-id >
        
< navigation-case >
            
< from-outcome > uploadedfile </ from-outcome >
            
< to-view-id > /upload/uploadlist.xhtml </ to-view-id >
        
</ navigation-case >
    
</ navigation-rule >
    
< managed-bean >
        
< managed-bean-name > upLoadBean </ managed-bean-name >
        
< managed-bean-class >
            com.lw.bean.UpLoadBean
        
</ managed-bean-class >
        
< managed-bean-scope > request </ managed-bean-scope >

    
</ managed-bean >
</ faces-config >

 

UpLoadBean类

package  com.lw.bean;

import  java.io.BufferedInputStream;
import  java.io.IOException;
import  java.io.InputStream;
import  javax.faces.application.FacesMessage;
import  javax.faces.context.FacesContext;
import  org.apache.myfaces.trinidad.model.UploadedFile;

public   class  UpLoadBean  {

    
private UploadedFile file;

    
public UploadedFile getFile() {
        
return file;
    }


    
public void setFile(UploadedFile file) {
        
this.file = file;
    }


    
public String uploadedfile() {

        
try {
            FacesContext context 
= FacesContext.getCurrentInstance();
            
//在控制台输出上传文件的文件名,和文件大小
            FacesMessage message = new FacesMessage(
                    
"Successfully uploaded file" + file.getFilename() + "("
                            
+ file.getLength() + "bytes)");
            context.addMessage(
null, message);

            InputStream stream;
            stream 
= new BufferedInputStream(file.getInputStream());
            
byte[] bytes = new byte[1024 * 1024];//设定文件大小
            @SuppressWarnings("unused")
            
int count;
            count 
= stream.read(bytes);
            stream.close();
//关闭流
            return "uploadedfile";
        }
 catch (IOException e) {
            e.printStackTrace();
            
return null;
        }

    }


}

 

上传页面upload.xhtml

<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html  xmlns ="http://www.w3.org/1999/xhtml"
    xmlns:ui
="http://java.sun.com/jsf/facelets"
    xmlns:u
="http://java.sun.com/blueprints/ui"
    xmlns:c
="http://java.sun.com/jsp/jstl/core"
    xmlns:h
="http://java.sun.com/jsf/html"
    xmlns:a4j
="https://ajax4jsf.dev.java.net/ajax"
    xmlns:f
="http://java.sun.com/jsf/core"
    xmlns:tr
="http://myfaces.apache.org/trinidad"  xml:lang ="en"  lang ="en" >
    
< head >
        
< title > My Facelets Page </ title >
        
< meta  http-equiv ="keywords"  content ="enter,your,keywords,here"   />
        
< meta  http-equiv ="description"
            content
="A short description of this page."   />
        
< meta  http-equiv ="content-type"  content ="text/html; charset=UTF-8"   />

        
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->

        
< script >
</ script >
    
</ head >
    
< body >
        
< f:view >

            
< tr:form  usesUpload ="true" >
                
< tr:inputFile  label ="上传:"  value ="#{upLoadBean.file}"   />
                
< tr:commandButton  text ="开始"  action ="#{upLoadBean.uploadedfile}"   />
            
</ tr:form >

        
</ f:view >

    
</ body >
</ html >

 

显示上传文件的文件名和文件大小的页面uploadlist.xhtml

 

<? xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html  xmlns ="http://www.w3.org/1999/xhtml"
    xmlns:ui
="http://java.sun.com/jsf/facelets"
    xmlns:h
="http://java.sun.com/jsf/html"
    xmlns:f
="http://java.sun.com/jsf/core"  xml:lang ="en"  lang ="en" >
    
< head >
        
< title > My Facelets Page </ title >
        
< meta  http-equiv ="keywords"  content ="enter,your,keywords,here"   />
        
< meta  http-equiv ="description"
            content
="A short description of this page."   />
        
< meta  http-equiv ="content-type"  content ="text/html; charset=UTF-8"   />

        
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
    
</ head >
    
< body >
        
< f:view >

            
< h:panelGrid  border ="0"  columns ="2"  style ="width: 411px" >
                
< h:outputText  value ="文件名:"   />
                
< h:outputText  value ="#{upLoadBean.file.filename}"   />
                
< h:outputText  value ="文件大小:"   />
                
< h:outputText  value ="#{upLoadBean.file.length}"   />
            
</ h:panelGrid >

        
</ f:view >
    
</ body >
</ html >

 

现在功能已经实现了,不过这个程序上传的文件成功后,会把文件变成tmp文件,不过我需要的功能已经实现了,因为我上传的是excel和work文件,然后用POI解析tmp文件,把它存入数据库就可以了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
依赖的文件: tomahawk-1.1.3.jar commons-fileupload-1.2.jar commons-io-1.3.1.jar Tomahawk.tld 把这个三个包放在/WEB_INF/lib目录下面。Jsf依赖的包也放在这个目录下面 Tomahawk.tld放在/WEB-INF目录下。Jsf标签也放在这个目录下面。 这个主要讲jsf上传文件,因此只罗列了上传文件用到的包和标签。 Web-xml文件如下: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <!-- Context Listener creates and sets the application handler --> <!-- Faces Servlet --> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- Faces Servlet Mapping --> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <filter> <filter-name>ExtensionsFilter</filter-name> <filter-class> org.apache.myfaces.component.html.util.ExtensionsFilter </filter-class> <init-param> <param-name>uploadMaxFileSize</param-name> <param-value>10m</param-value> </init-param> <init-param> <param-name>uploadThresholdSize</param-name> <param-value>100k</param-value> </init-param> </filter> <filter-mapping> <filter-name>ExtensionsFilter</filter-name> <!—要和<servlet-mapping>中的<servlet-name>一致--> <servlet-name>Faces Servlet</servlet-name> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> 上传文件的页面如下: <%@ include file="tags.jsp"%> <f:view> <h:form id="MyForm" enctype="multipart/form-data" > <h:messages globalOnly="true" styleClass="message"/> <h:panelGrid columns="3" border="0" cellspacing="5"> <h:outputLabel for="myFileId" value="File: "/> <x:inputFileUpload id="myFileId" value="#{myBean.myFile}" storage="file" required="true"/> <h:message for="myFileId"/> <h:outputLabel for="myParamId" value="Param: "/> <h:selectOneMenu id="myParamId" value="#{myBean.myParam}" required="true"> <f:selectItem itemLabel="" itemValue=""/> <f:selectItem itemLabel="MD5" itemValue="MD5"/> <f:selectItem itemLabel="SHA-1" itemValue="SHA-1"/> <f:selectItem itemLabel="SHA-256" itemValue="SHA-256"/> <f:selectItem itemLabel="SHA-384" itemValue="SHA-384"/> <f:selectItem itemLabel="SHA-512" itemValue="SHA-512"/> </h:selectOneMenu> <h:message for="myParamId"/> <h:outputText value=" "/> <h:commandButton value="Submit" action="#{myBean.processMyFile}"/> <h:outputText value=" "/> </h:panelGrid> </h:form> </f:view> 其中tags.jsp文件如下: <%@ page language="java" pageEncoding="GB18030"%> <%@ page contentType="text/html" %> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="x"%> Faces-config.xml文件如下: <faces-config> <managed-bean> <managed-bean-name>myBean</managed-bean-name> <managed-bean-class> fileupload.MyBean </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean> </faces-config> MyBean如下: package com.dhc; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.InputStream; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import org.apache.myfaces.custom.fileupload.UploadedFile; public class oaMailMainForm { private UploadedFile myFile; public UploadedFile getMyFile() { return myFile; } public void setMyFile(UploadedFile myFile) { this.myFile = myFile; } public String uploadedfile() { System.out.println("Entry"); try { InputStream in = new BufferedInputStream(myFile.getInputStream()); try { byte[] buffer = new byte[64 * 1024]; FileOutputStream fileOutputStream = new FileOutputStream( "C:\\My Files\\tst.jpg");// 这里可以把上传的文件写服务器目录,或者数据库中 while (in.read(buffer) > 0) { fileOutputStream.write(buffer); } } finally { in.close(); } System.out.println("End"); return "success"; } catch (Exception x) { System.out.print("Exception"); FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_FATAL, x.getClass().getName(), x .getMessage()); FacesContext.getCurrentInstance().addMessage(null, message); return null; } } } 参考文献:http://www.blogjava.net/cooky/archive/2007/10/02/150176.html http://blog.csdn.net/meteorlWJ/archive/2008/01/09/2032505.aspx http://tml808.javaeye.com/blog/166853
由于JSF2.0标准实现没有提供文件上传组件,而实际应用中很多时候需要上传文件,为了方便开发,我做了一个基于JSF2.0的文件上传组件,上传使用的是Apache 的commons-fileupload组件,我已经将commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar打包成一个lfaces.jar文件,使用时无需导入这两个jar文件,我使用的是Facelets技术,使用时很简单,导入命名空间后就可以使用标签(<l:inputFile/>)了,这个标签和<h:inputText/>标签使用方法一样,具体请参考例子。补充说明:是以临时文件存放在服务器上的,上传后需要自行处理,响应之前(JSF处理完毕)将会删除该临时文件,要设置上传的参数,比如文件存放目录,上传大小等,请在源目录(src)下建一个名为uploadfile.properties的文件,内容如下: #设置用于存放用户上传的文件夹,可以是绝对路径,例:C:/upload,也可是相对路径,例:/upload, #文件上传后是以.tmp为后缀的临时文件存储在服务器上,请求处理完成后系统将自动删除该临时文件,需要自行保存文件到需求的目录 uploadFile.path=E:/ #设置上传文件总大小的上限 uploadFile.sizeMax=1024*1024*50 #设置上传文件大小的上限 uploadFile.fileSizeMax=1024*1024*10 #设置缓存大小,如果文件大于缓存大小时,则先把文件放到缓存中 uploadFile.sizeThreshold=1024*1024 #设置上传文件类型 uploadFile.extFilter=.jpg|.jpeg|.gif|.bmp|.png|.xls|.doc|.txt
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值