把上传的文件作为一个输入流对象读入,再写到一个输出流对象中,
从而生成一个和上传文件一样的文件,原理和文件的复制类似。
②上传通用函数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。