JSF上传多个文件的文件

 

基本思路:<t:dataTable>内部放置<t:inputFileUpload>,根据设定的上传文件数,构造dataTable的List。
说明:以下代码包含了文件上传以外的相关代码,不做整理了。

实现目标:

< html >
< head >
< title > uploadfile </ title >
< meta  http-equiv ="Content-Type"  content ="text/html; charset=gb2312" >
< style  type ="text/css" >
<!--
td 
{   font-size :  9pt }
{   color :  #000000 ;  text-decoration :  none }
a:hover 
{   text-decoration :  underline }
.tx 
{   height :  16px ;  width :  30px ;  border-color :  black black #000000 ;  border-top-width :  0px ;  border-right-width :  0px ;  border-bottom-width :  1px ;  border-left-width :  0px ;  font-size :  9pt ;  background-color :  #eeeeee ;  color :  #0000FF }
.bt 
{   font-size :  9pt ;  border-top-width :  0px ;  border-right-width :  0px ;  border-bottom-width :  0px ;  border-left-width :  0px ;  height :  16px ;  width :  80px ;  background-color :  #eeeeee ;  cursor :  hand }
.tx1 
{  height :  20px ;  width :  30px ;  font-size :  9pt ;  border :  1px solid ;  border-color :  black black #000000 ;  color :  #0000FF }
-->
</ style >
< script  language ="JavaScript" >
<!--
self.moveTo(
0 , 0 )
self.resizeTo(screen.availWidth,screen.availHeight)
// -->
</ script >
</ head >

< body  bgcolor ="#FFFFFF"  text ="#000000"  background ="bj.gif" >
< form  name ="form1"  method ="post"  action ="upfile.asp"  enctype ="multipart/form-data"   >
  
< input  type ="hidden"  name ="act"  value ="upload" >
  
< table  width ="76%"  border ="1"  cellspacing ="0"  cellpadding ="5"  align ="center"  bordercolordark ="#CCCCCC"  bordercolorlight ="#000000"  height ="182" >
    
< tr  bgcolor ="#CCCCCC" >  
      
< td  height ="22"  align ="left"  valign ="middle"  bgcolor ="#CCCCCC" >
 文件上传
</ td >
    
</ tr >
    
< tr  align ="left"  valign ="middle"  bgcolor ="#eeeeee" >  
      
< td  bgcolor ="#eeeeee"  height ="1" >  
        
< script  language ="javascript" >
      
function  setid()
      {
      str
= ' <br> ' ;
      
if ( ! window.form1.upcount.value)
       window.form1.upcount.value
= 1 ;
       
for (i = 1 ;i <= window.form1.upcount.value;i ++ )
         str
+= ' 文件 ' + i + ' :<input type="file" name="file ' + i + ' " style="width:400" class="tx1"><br><br> ' ;
      window.upid.innerHTML
= str;
      }
      
</ script >
        
< li >  需要上传的个数 
          
< input  type ="text"  name ="upcount"  class ="tx"  value ="1" >
          
< input  type ="button"  name ="Button"  class ="bt"  onclick ="setid();"  value ="· 设定 ·" >
        
</ li >
      
</ td >
    
</ tr >
    
< tr  align ="center"  valign ="middle" >  
      
< td  align ="left"  id ="upid"  height ="32" >  文件1:        
        
< input  type ="file"  name ="file1"  style ="width:403; height:20"  class ="tx1"  value ="" ></ td >
    
</ tr >
    
< tr  align ="center"  valign ="middle"  bgcolor ="#eeeeee" >  
      
< td  bgcolor ="#eeeeee"  height ="28" >  
        
< input  type ="submit"  name ="Submit"  value ="· 提交 ·"  class ="bt" >
        
< input  type ="reset"  name ="Submit2"  value ="· 重置 ·"  class ="bt" ></ td >
    
</ tr >
  
</ table >
</ form >
</ body >
</ html >



jsp:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
<% @page language="java" contentType="text/html; charset=gb2312" %>
<% @taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<% @taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<% @taglib prefix="t" uri="http://myfaces.apache.org/tomahawk" %>
< f:loadBundle  basename ="batsys.resources.batsys"  var ="batsys"   />
< h:form >
    
< h:panelGrid  width ="100%"  columns ="5"  border ="1"
        styleClass
="scrollerTable2" >
        
< f:facet  name ="header" >
            
< h:outputText  value ="#{batsys['fttx.FT1001.wjsc']}"   />
        
</ f:facet >

        
< h:outputText  value ="#{batsys['fttx.FT1001.ywlx']}"   />
        
< h:selectOneMenu  value ="#{FT1001.bizType}"  styleClass ="SELECT" >
            
< f:selectItems  value ="#{FT1001.bizTypeItems}"   />
        
</ h:selectOneMenu >

        
< h:outputText  value ="#{batsys['fttx.FT1001.filecount']}"   />
        
< h:panelGroup >
            
< h:inputText  value ="#{FT1001.upcount}"  id ="upcount" >
                
< f:validateLongRange  maximum ="#{FT1001.maxUpCount}"   />
            
</ h:inputText >
            
< h:message  for ="upcount"  styleClass ="error"   />
        
</ h:panelGroup >

        
< h:commandButton  value ="#{batsys['fttx.FT1001.setcount']}"
            action
="FT1001_1"   />

        
< h:outputText  value ="#{batsys['fttx.FT1001.sh']}"   />
        
< h:selectOneListbox  value ="#{FT1001.branchNo}"  size ="1" >
            
< f:selectItems  value ="#{FT1001.branchItems}"   />
        
</ h:selectOneListbox >
    
</ h:panelGrid >
</ h:form >
< h:form  enctype ="multipart/form-data" >
    
< t:dataTable  value ="#{FT1001.fileUploadList}"  var ="fileUploadList"
        width
="100%"  border ="1"  align ="center"  columnClasses ="center,center" >
        
< h:column >
            
< h:outputText  value ="#{fileUploadList.xh}"   />
        
</ h:column >
        
< h:column >
            
< t:inputFileUpload  value ="#{fileUploadList.uploadedFile}"
                required
="true"  id ="uploadedFile"   />
            
< h:message  for ="uploadedFile"  styleClass ="error"   />
        
</ h:column >
    
</ t:dataTable >
    
< h:panelGrid  width ="100"  columns ="1"  cellspacing ="0"  cellpadding ="5"
        columnClasses
="right,left"  align ="center" >
        
< h:commandButton  value ="#{batsys['GL1001.uploadfile']}"
            action
="#{FT1001.storeFile}"  styleClass ="button"   />
    
</ h:panelGrid >
</ h:form >

BackingBean:

package  batsys.backingbean.fttx;

import  java.io.File;
import  java.io.IOException;
import  java.util.ArrayList;
import  java.util.Iterator;
import  java.util.LinkedList;
import  java.util.List;

import  javax.faces.model.SelectItem;

import  org.apache.myfaces.custom.fileupload.UploadedFile;

import  batsys.biz.BSGL1001;
import  batsys.biz.common.FindBranchInfo;
import  batsys.biz.common.SearchEnums;
import  batsys.enums.EBizType;
import  ccbxj.app.AppBackingBean;
import  ccbxj.app.AppContext;
import  ccbxj.app.web.security.util.WebSecurityUtil;
import  ccbxj.dbtable.TNBICodeTran;
import  ccbxj.dbtable.TNBranch;
import  ccbxj.ss.SSResource;

public   class  FT1001  extends  AppBackingBean  {
    
// 同时上传文件的个数
    private int upcount;

    
// 允许同时上传文件的最大个数,初值在配置BackingBean时定义
    private int maxUpCount;

    
private int bizType;

    
private String branchNo;

    
// 放置FT1001VO(上传文件VO)的集合
    private List fileUploadList;

    
private List bizTypeItems = null;

    
private List branchItems = null;

    AppContext ac 
= WebSecurityUtil.getAppContext();

    
public void setFileUploadList(List fileUploadList) {
        
this.fileUploadList = fileUploadList;
    }


    
public int getUpcount() {
        
return upcount;
    }


    
public void setUpcount(int upcount) {
        
this.upcount = upcount;
    }


    
public int getBizType() {
        
return bizType;
    }


    
public void setBizType(int bizType) {
        
this.bizType = bizType;
    }


    
/**
     * 遍历上传文件的集合,并批量上传到服务器磁盘
     * 
     * 
@return null
     
*/

    
public String storeFile() {
        BSGL1001 bsgl1001 
= new BSGL1001();
        
try {
            
if (fileUploadList != null{
                
for (Iterator iter = fileUploadList.iterator(); iter.hasNext();) {
                    FT1001VO ft1001VO 
= (FT1001VO) iter.next();
                    UploadedFile uploadedFile 
= ft1001VO.getUploadedFile();
                    String of 
= BSGL1001.uploadFileName(uploadedFile.getName()); // 文件的原始名称
                    File saveFile = new File(BSGL1001.uploadPath(SSResource
                            .getUploadPath(), ac)
                            
+ File.separator + of);
                    bsgl1001.saveFile(ft1001VO.getUploadedFile(), saveFile);
                }

            }

        }
 catch (IOException e) {
            e.printStackTrace();
        }
 catch (Exception e) {
            e.printStackTrace();
        }

        
return null;
    }


    
/**
     * 根据设定的上传文件数,构造dataTable的List
     * 
     * 
@return List
     
*/

    
public List getFileUploadList() {
        fileUploadList 
= new ArrayList();
        FT1001VO ft1001VO 
= null;
        String str 
= "文件";
        
for (int i = 1; i <= upcount; i++{
            ft1001VO 
= new FT1001VO();
            ft1001VO.setXh(str 
+ i + ":");
            fileUploadList.add(ft1001VO);
        }

        
return fileUploadList;
    }


    
/**
     * 查询枚举表,为业务类型下拉列表准备数据
     * 
     * 
@return List
     
*/

    
public List getBizTypeItems() {
        
try {
            SearchEnums se 
= SearchEnums.getInstance();
            List bizTypeList 
= null;
            bizTypeList 
= se.getEnumsByClassName(EBizType.class.getName());
            bizTypeItems 
= new LinkedList();
            
if (bizTypeList != null{
                
for (Iterator iter = bizTypeList.iterator(); iter.hasNext();) {
                    TNBICodeTran tnbicodeTran 
= (TNBICodeTran) iter.next();
                    bizTypeItems.add(
new SelectItem(tnbicodeTran.getCode(),
                            tnbicodeTran.getName()));
                }

                setBizTypeItems(bizTypeItems);
            }

        }
 catch (Exception e) {
            e.printStackTrace();
            
this.throwException(ac, e, this.getClass().getName(),
                    
"getBizTypeItems""查询业务类型的下拉列表时抛出Exception");
        }

        
return bizTypeItems;
    }


    
public void setBizTypeItems(List bizTypeItems) {
        
this.bizTypeItems = bizTypeItems;
    }


    
/**
     * 根据部门编码取得下级部门列表,用于文件上传交易第一个页面的部门(所号)列表
     * 
     * 
@return List
     
*/

    
public List getBranchItems() {
        
try {
            List branchList 
= null;
            branchList 
= FindBranchInfo.getInstance().getBranchList("xj",
                    ac.getBranchCode());
            branchItems 
= new LinkedList();
            
if (branchList != null{
                
for (Iterator iter = branchList.iterator(); iter.hasNext();) {
                    TNBranch branch 
= (TNBranch) iter.next();
                    branchItems.add(
new SelectItem(branch.getBranchNo(), branch
                            .getBranchNo()
                            
+ "(" + branch.getBranchName() + ")"));
                }

                setBranchItems(branchItems);
            }

        }
 catch (Exception e) {
            e.printStackTrace();
            
this.throwException(ac, e, this.getClass().getName(),
                    
"getBranchItems""查询部门列表时抛出Exception,当前机构号为:"
                            
+ ac.getBranchCode());
        }

        
return branchItems;
    }


    
public void setBranchItems(List branchItems) {
        
this.branchItems = branchItems;
    }


    
public String getBranchNo() {
        
return branchNo;
    }


    
public void setBranchNo(String branchNo) {
        
this.branchNo = branchNo;
    }


    
public int getMaxUpCount() {
        
return maxUpCount;
    }


    
public void setMaxUpCount(int maxUpCount) {
        
this.maxUpCount = maxUpCount;
    }


}

VO:

package  batsys.backingbean.fttx;

import  org.apache.myfaces.custom.fileupload.UploadedFile;

/**
 * 类名: FT1001VO
 * <p>
 * 功能说明:存储dataTable的一行数据
 * 
 * 
@version 1.0 2006-9-29
 
*/


public   class  FT1001VO  {
    
// 文件上传的序号,如文件1,文件2
    private String xh;

    
private UploadedFile uploadedFile;

    
public UploadedFile getUploadedFile() {
        
return uploadedFile;
    }


    
public void setUploadedFile(UploadedFile uploadedFile) {
        
this.uploadedFile = uploadedFile;
    }


    
public String getXh() {
        
return xh;
    }


    
public void setXh(String xh) {
        
this.xh = xh;
    }

}

保存文件到硬盘的方法:

/**
     * saveFile 保存文件到硬盘
     * 
     * 
@param uploadedFile
     *            UploadedFile
     * 
@param savefile
     *            File 此文件必须创建存在
     * 
@throws IOException
     * 
@throws IOException
     
*/

    
public   void  saveFile(UploadedFile uploadedFile, File savefile)
            
throws  IOException  {
        
byte buff[] = null;
        
//
        File md = savefile.getParentFile();
        
if (!md.exists()) {
            md.mkdirs();
        }

        
//
        long fs = uploadedFile.getSize();
        FileOutputStream fos 
= new FileOutputStream(savefile);
        
if (fs > 1025 * 1024 * 10// the upload file is more than 10M byte
            buff = new byte[1025 * 500]; // set buff 500k byte
        }
 else {
            buff 
= new byte[1025 * 100]; // set buff 100k byte
        }

        InputStream is 
= uploadedFile.getInputStream();
        
int rb = 0;
        rb 
= is.read(buff);
        
while (rb > 0{
            fos.write(buff, 
0, rb);
            rb 
= is.read(buff);
        }

        fos.close();
    }

faces-config.xml的配置片段:


< managed-bean >
        
< managed-bean-name > FT1001 </ managed-bean-name >
        
< managed-bean-class >
            batsys.backingbean.fttx.FT1001
        
</ managed-bean-class >
        
< managed-bean-scope > session </ managed-bean-scope >
        
< managed-property >
            
< property-name > upcount </ property-name >
            
< value > 1 </ value >
        
</ managed-property >
        
< managed-property >
            
< property-name > maxUpCount </ property-name >
            
< value > 10 </ value >
        
</ managed-property >
    
</ managed-bean >
    < navigation-case >
            
< from-outcome > FT1001_1 </ from-outcome >
            
< to-view-id > /jsp/FT1001_1.jsf </ to-view-id >
    
</ navigation-case >
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
依赖的文件: 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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值