struts上传文件

来源:互联网 发布:江苏网络教育成绩查询 编辑:程序博客网 时间:2024/06/07 17:15

 1.上传的jsp页面代码_uploadfiles.jsp

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>上传文件</title>
</head>
<body>
<logic:messagesPresent>
        
<table width="100%">
            
<tr>
                
<td align = center >
                    
<ul>
                    
<bean:message key="errors.header" />
                    
<html:messages id="error"><li><bean:write name="error" /></li>
                    
</html:messages>
                    
</ul>
                
</td>
            
</tr>
        
</table>
        
</logic:messagesPresent>  
  
  
        
<html:form action="/uploadfile.do?action=addfile" enctype="multipart/form-data" method="post"> 
        
<table align="center" width="200px" >
            
<tr>
                
<td nowrap="nowrap">文件名:</td>
                
<td><html:file property="filename" /></td>
            
</tr>
            
<tr>
                
<td nowrap="nowrap">备注</td>
                
<td><html:textarea property="memo" /></td>
            
</tr>
            
<tr>
                
<td colspan="2" align="center">
                    
<html:submit>增加资料</html:submit>
                    
<html:reset>重写</html:reset>
                
</td>
            
</tr>
        
</table>
      
</html:form>
</body>
</html>

2.Action文件_UploadfileAction.java

 

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 
*/

package com.mk.struts.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;

import com.mk.bean.ConvertImage;
import com.mk.struts.dao.BookDAO;
import com.mk.struts.dao.FileDAO;
import com.mk.struts.filter.CharFilter;
import com.mk.struts.form.UploadfileForm;

/** 
 * MyEclipse Struts
 * Creation date: 01-10-2007
 * 
 * XDoclet definition:
 * @struts.action path="/uploadfile" name="uploadfileForm" input="/file/uploadfiles.jsp" scope="request" validate="true"
 
*/

public class UploadfileAction extends Action {
    
/*
     * Generated Methods
     
*/


    
/** 
     * Method execute
     * 
@param mapping
     * 
@param form
     * 
@param request
     * 
@param response
     * 
@return ActionForward
     
*/

    
public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) 
    
{
        UploadfileForm uploadfileForm 
= (UploadfileForm) form; // TODO Auto-generated method stub
        
        FormFile filename 
= uploadfileForm.getFilename() ;
        String   memo     
= CharFilter.toChinese(uploadfileForm.getMemo()) ;
        
        DataSource ds 
= null ;
        Connection conn 
= null ;
        HttpSession session 
= null ;
        
        
        
        
try
        
{
            ds 
= getDataSource(request , "A") ;
            conn 
= ds.getConnection() ;
            
            FileDAO sqlDao 
= new FileDAO(conn) ;
            
            String action 
= request.getParameter("action") ;
            ActionMessages errors 
= new ActionMessages() ;
            
        
            
//增加文件
            if ( action.equals("addfile"))
            
{
                
//传递文件
                if ( filename.getFileName().trim().length() > 0 )
                
{
//                    取得上传时间
                    SimpleDateFormat DateFormat1 = new SimpleDateFormat("yyyy-MM-dd"); 
                    Date dt 
= new Date() ;
                    String uptime 
= DateFormat1.format(dt) ;
                    
                    String tempname 
= "" ;
                    
try
                    
{
                         
//开始上传文件
                         String filePath = this.getServlet().getServletContext().getRealPath("/") ; //取得当前路径
                         InputStream stream = filename.getInputStream() ; //把文件读入
                                
                         
// ByteArrayOutputStream baos = new ByteArrayOutputStream() ;                                
                         /*
                           * 建立一个上传文件的输出流如果是linux系统请把"/" 换成 "/"
                         
*/

                                
                         System.out.println(filename.getFileName()) ;
                         
                         
int position = filename.getFileName().indexOf(".") ;
                         String type 
= filename.getFileName().substring(position);
                         
                         String fileid 
= sqlDao.getMaxFileID() ;
                         
                         tempname 
= fileid + type ;
                         
                                
                         OutputStream bos 
= new FileOutputStream(filePath + "file/upfiles/" + tempname ) ;
                                
                         
//request.setAttribute("fileName",filePath + "/" + CharFilter.toChinese((String)filename.getFileName()) ) ;
                         int bytesRead = 0 ;
                         
byte[] buffer = new byte[8192] ;
                         
while( (bytesRead = stream.read(buffer,0,8192) ) != -1  )
                         
{
                             bos.write(buffer,
0,bytesRead) ;
                         }

                                
                         bos.close();
                         stream.close() ;    
                                
                         
//上传文件完成
                         
                     }

                            
                     
catch(Exception e)
                     
{
                         errors.add(ActionMessages.GLOBAL_MESSAGE , 
new ActionMessage("file.add.failure")) ;
                         
if ( !errors.isEmpty()) { saveErrors(request, errors) ;}
                         
return new ActionForward(mapping.getInput()) ;
                     }

                    
                    
                    
//写入记录
                    if (!sqlDao.insertNewFile(tempname , filename.getFileName(), memo, uptime))
                    
{
                        errors.add(ActionMessages.GLOBAL_MESSAGE , 
new ActionMessage("file.add.failure")) ;
                        
if ( !errors.isEmpty()) { saveErrors(request, errors) ;}    
                        
return new ActionForward(mapping.getInput()) ;
                    }
            
                    
                    
                    removeFormBean(mapping, request) ;                
                    
return new ActionForward(mapping.getInput()) ;    
                
                }
                
            }
    
            
if ( action.equals("listfiles"))
            
{
                request.setAttribute(
"file", sqlDao.getAllFiles() ) ;    
                removeFormBean(mapping , request ) ;
                
return mapping.findForward("listfiles") ;
            }

            
if ( action.equals("del")  )
            
{
                String id 
= request.getParameter("id") ;
                String name 
= CharFilter.toChinese(request.getParameter("name") );
                
                
//删除文件
                String filePath = this.getServlet().getServletContext().getRealPath("/"+ "file/upfiles/" ; //取得当前路径
                
                File thisFile 
= new File(filePath , name ) ;
                
                
if ( thisFile.exists())
                
{
                    thisFile.delete() ;
                }

                
//删除数据库文件                
                sqlDao.delfile(id) ;
                
                
return mapping.findForward("success") ;
            }

            
        }

        
catch( SQLException e )
        
{
            e.printStackTrace() ;
        }

        
finally
        
{
            
try 
            
{
                
if ( conn != null )
                
{
                    conn.close() ;
                }
                
            }

            
catch(SQLException e )
            
{
                e.printStackTrace() ;
            }

        }

        
        
return null ;
    }

    
    
    
protected void removeFormBean(ActionMapping mapping, HttpServletRequest request)
    
{
        
if(mapping.getAttribute() != null)
            
if("request".equals(mapping.getScope()))
            
{
                request.removeAttribute(mapping.getAttribute());
            }
 else
            
{
                HttpSession session 
= request.getSession();
                session.removeAttribute(mapping.getAttribute());
            }

    }

}

 

3.数据DAO文件,FileDAO.java

 

package com.mk.struts.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.beanutils.RowSetDynaClass;

import com.mk.bean.CustomRowSetDynaClass;

public class FileDAO {
    
    
private Connection conn         = null ;
    
private String        sql          = "" ;
    
private Statement  stmt         = null ;
    
private PreparedStatement ps     = null ;
    
private ResultSet rs             = null ;
    
    
//    构造函数
    public FileDAO( Connection conn )
    
{
        
this.conn = conn ;
    }

    
//    增加文件
    public boolean insertNewFile(String filename , String truename ,  String memo , String uptime)
    
{
        
boolean bsuccess = true ;
        
        
try
        
{
            conn.setAutoCommit(
true) ;
            stmt 
= conn.createStatement() ;
            
//ID号不用加,ID号是自动增加的
            
//String name_id = CharFilter.toChinese(forms.getName_id()) ;
            
            sql 
= "insert into file (filename , truename ,  memo , uptime)" +
                  
" values ('" + filename + "','" + truename + "','" + memo +"','" + uptime + "')" ;
            
            stmt.execute(sql) ;                
        }

        
catch( SQLException e )
        
{
            e.printStackTrace() ;
            System.out.println(e.getMessage().toString()) ;
            bsuccess 
= false ;
            
            
throw new RuntimeException("运行发生错误!") ;
        }

        
finally 
        
{
            
try{
                    
if ( stmt != null )
                    
{
                        stmt.close() ;
                    }

                    
if ( rs != null )
                    
{
                        rs.close() ;
                    }

            }
catch(Exception e )
            
{
                e.printStackTrace() ;
                
throw new RuntimeException("运行发生错误!") ;
            }

        }

        
        
return bsuccess ;
    }

    
    
//得到全部文件
    public List getAllFiles()
    
{
        sql 
=  "select * from file " ;
        
        
return this.getRecords(sql) ;
    }

    
    
//通用函数
    public List getRecords(String sql )
    
{
        List rows 
= null ;
        
        
try
        
{
            ps 
= conn.prepareStatement(sql , ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_UPDATABLE) ;
            rs 
= ps.executeQuery() ;
            RowSetDynaClass rsdc 
= new RowSetDynaClass(rs) ;
            rows 
= rsdc.getRows();
        }

        
catch(SQLException ex )
        
{
            ex.printStackTrace() ;            
        }

        
finally
        
{
            
try
            
{
                
if ( rs != null ) rs.close() ;
                
if ( ps != null ) ps.close() ;                
            }

            
catch(SQLException ex )
            
{
                ex.printStackTrace() ;
            }

        }
        
        
return rows ;
    }

    
    
//按分页数得到记录值
    public List getPageRecords(String sql , int iCurPage ,int iNumPerPage )
    
{
        List rows 
= null ;
        
        
try
        
{
            ps 
= conn.prepareStatement(sql , ResultSet.TYPE_SCROLL_SENSITIVE , ResultSet.CONCUR_UPDATABLE) ;
            rs 
= ps.executeQuery() ;
            CustomRowSetDynaClass rsdc 
= new CustomRowSetDynaClass(rs,iCurPage , iNumPerPage ) ;
            rows 
= rsdc.getRows();
        }

        
catch(SQLException ex )
        
{
            ex.printStackTrace() ;            
        }

        
finally
        
{
            
try
            
{
                
if ( rs != null ) rs.close() ;
                
if ( ps != null ) ps.close() ;                
            }

            
catch(SQLException ex )
            
{
                ex.printStackTrace() ;
            }

        }
        
        
return rows ;
    }

    
    
    
//删除文件
    public boolean delfile(String id )
    
{
        
boolean bSuccess = true ;
        
        
        
//下面是删除数据库记录        
        try
        
{
            conn.setAutoCommit(
true) ;
            stmt 
= conn.createStatement() ;
            
//ID号不用加,ID号是自动增加的
            sql = "delete from file where id=" + id ;            
            stmt.execute(sql) ;            
            
        }
catch( SQLException e )
        
{
            e.printStackTrace() ;
            System.out.println(e.getMessage().toString()) ;
            bSuccess 
= false ;
            
throw new RuntimeException("运行发生错误!") ;
        }

        
finally 
        
{
            
try{
                
if ( stmt != null )
                
{
                    stmt.close() ;
                }

            }
catch(Exception e )
            
{
                e.printStackTrace() ;
                
throw new RuntimeException("运行发生错误!") ;
            }

        }

        
        
return bSuccess ;
    }

    
    
//得到文件的最大ID号
    public String getMaxFileID()
    
{
        String id
="" ;
        
try
        
{
            conn.setAutoCommit(
true) ;
            stmt 
= conn.createStatement() ;
            sql 
= "select max(id) from file " ; 
        
            ResultSet rs 
= stmt.executeQuery(sql) ;
            
            
if (rs.next())
            
{
                id 
= Integer.toString(rs.getInt("max(id)"+ 1)  ;
            }

            
        }
catch(SQLException e )
        
{
            e.printStackTrace() ;
            
throw new RuntimeException("查找文件发生错误!") ;
        }
finally
        
{
            
try
            
{
                
if ( stmt != null ) stmt.close() ;
                
if ( rs != null )  rs.close() ;
            }
catch( Exception e )
            
{
                e.printStackTrace() ;
                
throw new RuntimeException("运行发生错误!") ;
            }

        }

        
        
return id ;
        
    }


}

4.UploadfileForm.java

 

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 
*/

package com.mk.struts.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

/** 
 * MyEclipse Struts
 * Creation date: 01-10-2007
 * 
 * XDoclet definition:
 * @struts.form name="uploadfileForm"
 
*/

public class UploadfileForm extends ActionForm {
    
/*
     * Generated fields
     
*/


    
/** memo property */
    
private String memo;

    
/** filename property */
    
private FormFile filename;

    
/*
     * Generated Methods
     
*/


    
/** 
     * Method validate
     * 
@param mapping
     * 
@param request
     * 
@return ActionErrors
     
*/

    
public ActionErrors validate(ActionMapping mapping,
            HttpServletRequest request) 
{
        
// TODO Auto-generated method stub
        return null;
    }


    
/** 
     * Method reset
     * 
@param mapping
     * 
@param request
     
*/

    
public void reset(ActionMapping mapping, HttpServletRequest request) {
        
// TODO Auto-generated method stub
    }


    
/** 
     * Returns the memo.
     * 
@return String
     
*/

    
public String getMemo() {
        
return memo;
    }


    
/** 
     * Set the memo.
     * 
@param memo The memo to set
     
*/

    
public void setMemo(String memo) {
        
this.memo = memo;
    }


    
/** 
     * Returns the filename.
     * 
@return String
     
*/

    
public FormFile getFilename() {
        
return filename;
    }


    
/** 
     * Set the filename.
     * 
@param filename The filename to set
     
*/

    
public void setFilename(FormFile filename) {
        
this.filename = filename;
    }

}

 

5.数据库用mysql,用于存放文件信息.包括id , filename , truename,memo,uptime几个字段.

6.struts-config.xml的数据库配置

 

  <data-sources >
    
<data-source key="A" type="org.apache.commons.dbcp.BasicDataSource">
      
<set-property property="password" value="密码" />
      
<set-property property="username" value="用户" />
      
<set-property property="driverClassName" value="com.mysql.jdbc.Driver" />
      
<set-property property="url" value="jdbc:mysql://服务器:3306/数据库名" />
    
</data-source>
  
</data-sources>
.
.
.
.
.
<action
      attribute="uploadfileForm"
      input="/file/uploadfiles.jsp"
      name="uploadfileForm"
      path="/uploadfile"
      scope="request"
      type="com.mk.struts.action.UploadfileAction">
      <forward name="listfiles" path="/file/listfiles.jsp" />
    </action>

7.显示上传的文件

 

<%@ page language="java" contentType="text/html; charset=gb2312"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>
<%
    response.setHeader(
"Pragma" , "No-cache" ) ;
    response.setHeader(
"Cache-Control" , "no-Cache" ) ;
    response.setDateHeader(
"Expires",0) ;
    response.setContentType(
"text/html;charset=gb2312"); 
    
//得到全局用户表
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>文件列表</title>
<link href="<%=request.getContextPath()%>/css/itsp.css"    rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%=request.getContextPath()%>/js/print.js"></script>
</head>
<body>
<table width="200" border="0" align="center"  >
          
<tr>
              
<th scope="col">文件列表</th>
          
</tr>
      
</table>
      
<table bgcolor="#CCCCFF" align=center border=0 cellpadding=1 cellspacing=1 width="100%" id="PrintTable" >
      
<tr>
          
<th nowrap="nowrap" bgcolor="#99CCFF" >文件名</th>
          
<th nowrap="nowrap" bgcolor="#99CCFF" >上传时间</th>
          
<th nowrap="nowrap" bgcolor="#99CCFF" >备注</th>
          <th nowrap="nowrap" bgcolor="#99CCFF" >操作</th>         </tr>  
          
<logic:iterate id="file" name="file" >
          
<tr  align="center" bgcolor="#ffffff" valign="middle" >
                  
<td class=tdsmall ><href="<%=request.getContextPath()%>/file/upfiles/<bean:write name="file" property="filename" />"><bean:write name="file" property="truename" filter="false"/></a></td>
                  
<td class=tdsmall ><bean:write name="file" property="uptime"  filter="false"/></td>
                  
<td class=tdsmall ><bean:write name="file" property="memo" filter="false" /></td>
                  
             
                  
<td class=tdsmall ><href="<%=request.getContextPath()%>/uploadfile.do?action=del&id=<bean:write name="file" property="id" />&name=<bean:write name="file" property="filename" />">删除</a></td>
          </tr>
          
</logic:iterate>    
        
<tr align="center" bgcolor="#ffffff" valign="middle">
            
<td colspan=4 class=tdsmall>
          
<href="<%=request.getContextPath()%>/file/uploadfiles.jsp" >上传文件</a>
          
</td>
      
</table>    

      
     
</body>
</html>

 

 收工!!!!

原创粉丝点击