struts的文件上传

  对于文件上传功能,struts提供了FormFile接口。

  功能实现包括2个页面,1个ActionForm和1个Action.配置如下:

ActionForm实现如下:

 

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


    
/**
     * 
     
*/

    
private static final long serialVersionUID = 4013695631391043303L;
    
/** theFile property */
    
private FormFile theFile;

    
/*
     * 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 theFile.
     * 
@return FormFile
     
*/

    
public FormFile getTheFile() {
        
return theFile;
    }


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

    
public void setTheFile(FormFile theFile) {
        
this.theFile = theFile;
    }

}

页面实现:

设置表单的enctype属性为:multipart/form-data

使用<html:file>标记生成文件上传的控件。

Action编写如下:

 

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) 
{
        UploadForm uploadForm 
= (UploadForm) form;// TODO Auto-generated method stub
        
        FormFile file 
= uploadForm.getTheFile();
        String fileName 
= file.getFileName();
        String contentType 
= file.getContentType();
        
int fileSize = file.getFileSize();
        
        System.out.println(
"类型:" + contentType);
        System.out.println(
"文件名: " + fileName);
        System.out.println(
"文件大小: " + fileSize);
        
        
try {
            
byte[] fileData = file.getFileData();
            FileOutputStream out 
= new FileOutputStream(new File("F://" + fileName));
            out.write(fileData);
            out.close();
        }
 catch (Exception e) {
            
// TODO 自动生成 catch 块
            e.printStackTrace();
        }
 
        
        
return mapping.findForward("success");
    }

}

通过上面的例子可以知道,FormFile对象可以得到上传文件的名称,类型,大小,内容等信息。

如果要文件需保存在服务器可用request.getRealPath("/upload")方法来获取工程目录下upload文件夹的物理路径.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值