jsf实现同时上传不定数量的文件

来源:互联网 发布:cdn加速服务域名是什么 编辑:程序博客网 时间:2024/06/07 06:39

基本思路:<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>

运行效果图:

原创粉丝点击