关于Struts中文件的上传

 ①实现原理:
把上传的文件作为一个输入流对象读入,再写到一个输出流对象中,
从而生成一个和上传文件一样的文件,原理和文件的复制类似。

②上传通用函数Action:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.struts.upload.FormFile;

protected void uploadFile( UploadForm form, String target ) throws exception {
    FormFile file = form.getTheFile();
   
    InputStream stream = null;
    OutputStream bos = null;
    try {
        stream = file.getInputStream();
        bos = new FileOutputStream( target );
        int bytesRead = 0;
        byte[] buffer = new byte[ 1024 ];
        while ( ( bytesRead = stream.read( buffer, 0, 1024 ) ) != -1 ) {
            bos.write( buffer, 0, bytesRead );
        }

    } catch ( FileNotFoundException fnfe ) {
        throw new exception( "" );

    } catch ( IOException ioe ) {
        throw new exception( "" );

    } finally {        
        try {            
            if ( stream != null ) {
                stream.close();
            }
           
            if ( bos != null ) {
                bos.close();
            }
        } catch ( IOException e ) {
            throw new exception( "" );

        }
    }

    file.destroy();
}

③上传Action:
try {
    this.uploadFile( 上传Form, 文件上传位置全路径 );
   
} catch ( exception e ) {
   
}
注意上传Action必须继承上传通用函数Action。

④上传通用Form:
import org.apache.struts.upload.FormFile;
public class UploadForm extends PageForm {
    private FormFile theFile;(及其getter和setter)
}

⑤上传jsp:
使用<html:file property="theFile"  />控件,注意上传Form必须继承上传通用Form。

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值