如何用struts上传文件,并限制文件扩展名和文件大小.

在做开发时难免会碰到上传文件,近来我就来和大家分享一下心得,供大家讨论.多提宝贵意见.

在struts中上传文件当然要用struts的标签了,<html:file>.用该标签是需要注意以下几点:

  1. <html:file> 该标签必须和,<html:form>一起使用并且必须嵌套在<html:form>中,其实struts的html标签必须要写在<html:form>中.
  2. <html:form>中的method属性必须是post.
  3. <html:form>的enctype属性必须是multipart/form-data
  4. <html:file>必须设置property属性,并且该属性的值必须和ActionFormBean 中的 org.apache.struts.upload.FormFile类型属性对应.

upload.jsp代码如下:

 

<%@ page language="java" pageEncoding="utf-8"%>

<% @ taglib uri="http://jakarta.apache.org/struts/tags-bean"
    prefix
="bean"
%>
<% @ taglib uri="http://jakarta.apache.org/struts/tags-html"
    prefix
="html"
%>
<% @ taglib uri="http://jakarta.apache.org/struts/tags-logic"
    prefix
="logic"
%>
<% @ taglib uri="http://jakarta.apache.org/struts/tags-tiles"
    prefix
="tiles"
%>
<% @ taglib uri="http://jakarta.apache.org/struts/tags-template"
    prefix
="template"
%>
<% @ taglib uri="http://jakarta.apache.org/struts/tags-nested"
    prefix
="nested"
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html locale="true">
<head>
    
<html:base />

    
<title>upload.jsp</title>

    
<meta http-equiv="pragma" content="no-cache">
    
<meta http-equiv="cache-control" content="no-cache">
    
<meta http-equiv="expires" content="0">
    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    
<meta http-equiv="description" content="This is my page">
    
<!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    
-->

</head>

<body>
    
<h3>
        上传文件测试
    
</h3>
    
<html:form action="upload.do" method="post" enctype="multipart/form-data">
        
<html:file property="file"></html:file><br>
        
<html:submit></html:submit>
    
</html:form>
</body>
</html:html>

(upload.jsp)

 

 大家注意upload.jsp中<html:file> 的property属性.该值和actionfrom的属性相同,HtmlfileForm代码如下

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

package  com.uploadtest.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: 02-29-2008
 * 
 * XDoclet definition:
 * 
 * @struts.form name="htmlfileForm"
 
*/

public class HtmlfileForm extends ActionForm  {
    
/*
     * Generated Methods
     
*/


    
private FormFile file;

    
public FormFile getFile() 
{
        
return
 file;
    }


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


    
/**
     * 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

    }

}

(HtmlfileForm)

然后就是最主要的处理代码部分代码如下(UploadAction),在该Action中做了很多处理,都有注释,自己看.

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

package  com.uploadtest.struts.action;

import
 java.io.FileOutputStream;
import
 java.io.InputStream;
import
 java.io.OutputStream;
import
 java.util.ArrayList;
import
 java.util.List;

import
 javax.servlet.http.HttpServletRequest;
import
 javax.servlet.http.HttpServletResponse;
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.upload.FormFile;

import
 com.uploadtest.struts.form.HtmlfileForm;

/**
 * MyEclipse Struts Creation date: 02-29-2008
 * 
 * XDoclet definition:
 * 
 * @struts.action path="/upload" name="htmlfileForm" input="/upload.jsp"
 *                scope="request" validate="true"
 
*/

public class UploadAction 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) 
{
        
// webapps/uploadtest/upload

        String dir = servlet.getServletContext().getRealPath("/upload");
        List
<String> list = new ArrayList<String>();//注意文件类型最好全部用小写

        list.add("jpg");
        list.add(
"jpeg"
);
        list.add(
"gif"
);
        list.add(
"bmp"
);
        
// 允许上传的文件类型列表可以写在配置文件中,通过xml的解析获得。


        
if (!dir.endsWith("/"))
            dir 
= dir.concat("/"
);
        HtmlfileForm htmlfileForm 
= (HtmlfileForm) form;//
 TODO Auto-generated
        
// method stub

        FormFile file = htmlfileForm.getFile();
        
if (file == null
{
            
return
 mapping.getInputForward();
        }

        String fname 
= file.getFileName();// 获取文件名
        int fsize = file.getFileSize();// 获取文件大小
        String ext = fname.substring(fname.lastIndexOf("."+ 1, fname.length());
        
// 获取文件类型,即扩展名,通过String类的substring方法截取字符串,lastIndexOf获取某个字符串最后出现的索引。

        ext = ext.toLowerCase();// 全部转换成小写。
        if (!list.contains(ext)) {// 判断该类型是否为允许上传的文件类型
            System.out.println("不支持该文件类型上传,该文件类型是:" + ext);
            
// 可以在此构建ActionMessage对象并返回页面显示错误

            return mapping.getInputForward();
        }

        
if (fsize > 1024 * 1024{// 判断文件大小是否为允许上传的大小。
            
// 可以在此构建ActionMessage对象并返回页面显示错误

            System.out.println("文件太大");
            
return
 mapping.getInputForward();
        }


        InputStream in 
= null;// 输入流用来读取用户上传文件
        OutputStream out = null;// 用来将用户上传文件存出在服务器特定目录中。
        try {
            in 
=
 file.getInputStream();
            out 
= new FileOutputStream(dir +
 fname);
            
int byteread = 0
;
            
byte[] bytes = new byte[8192
];
            
while ((byteread = in.read(bytes, 08192)) != -1
{
                out.write(bytes, 
0
, byteread);
            }

        }
 catch (Exception e) {
            System.out.println(e.getMessage());
            
return
 mapping.getInputForward();
        }
 finally {
            
try 
{
                in.close();
                out.close();
            }
 catch (Exception e) 
{
                System.out.println(e.getMessage());
                
return
 mapping.getInputForward();
            }

        }

        System.out.println(
"chenggong");
        
return mapping.findForward("suc"
);//suc只是一个成功跳转的设置.
    }

}

(UploadAction)

以下是struts的配置文件.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
    
<data-sources />
    
<form-beans>
        
<form-bean name="htmlfileForm"
            type
="com.uploadtest.struts.form.HtmlfileForm" />


    
</form-beans>

    
<global-exceptions />
    
<global-forwards />
    
<action-mappings>
        
<action attribute="htmlfileForm" input="/upload.jsp"
            name
="htmlfileForm" path="/upload" scope="request"
            type
="com.uploadtest.struts.action.UploadAction">
            
<forward name="suc" path="/suc.jsp" />
        
</action>


    
</action-mappings>
    
<controller processorClass="com.uploadtest.struts.util.CharSet"></controller>
    
< message-resources
        
parameter="com.uploadtest.struts.ApplicationResources" />


</struts-config>

以上是个人的一点愚见,如有不对,请指正.
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值