您的位置:首页 > 编程语言 > Java开发

关于Struts中文件的上传

2007-06-26 17:10 351 查看
①实现原理:
把上传的文件作为一个输入流对象读入,再写到一个输出流对象中,
从而生成一个和上传文件一样的文件,原理和文件的复制类似。
②上传通用函数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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: