strut2进行文件上传

SPARK 2009-09-15

文件上传:

创建步骤:

1.创建jsp文件FileUpload.jsp文件

2.创建action类并继承ActionSupport类

3.对配置文件信息进行修改

实例

创建jsp文件FileUpload.jsp文件

<%@pagelanguage="java"contentType="text/html;charset=GB2312"%>

<%@taglibprefix="s"uri="/struts-tags"%>

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">

<html>

<h1>文件上传</h1>

<s:formaction="fileUpload"method="post"enctype="multipart/form-data">

选择要上传的图片:

<s:filename="upload"></s:file>

<br>

<s:submitvalue="上传"></s:submit>

</s:form>

</html>

b.创建action类并继承ActionSupport类

packageact;

importcom.opensymphony.xwork2.ActionSupport;

importcom.opensymphony.xwork2.ActionContext;

importjava.sql.*;

importjava.text.SimpleDateFormat;

importjavax.sql.*;

importjavax.swing.JOptionPane;

importjavax.naming.*;

importjava.util.*;

importjava.util.regex.Pattern;

importorg.apache.struts2.ServletActionContext;

importjava.util.Date;

importjava.io.*;

/*

*@authorqihuasun

*FileUploadAction类实现文件上传

*/

publicclassFileUploadActionextendsActionSupport

{

privateFileupload;//上传的文件

privateStringfileName;

privateStringcontentType;

publicFilegetUpload()

{

returnupload;

}

publicvoidsetUpload(Fileupload)

{

this.upload=upload;

}

publicStringgetFileName()

{

returnfileName;

}

publicvoidsetFileName(StringfileName)

{

this.fileName=fileName;

}

publicStringgetContentType()

{

returncontentType;

}

publicvoidsetContentType(StringcontentType)

{

this.contentType=contentType;

}

publicStringUpload()throwsException

{

Stringstr=this.SUCCESS;

//获取文件名

Stringfile=upload.getName();

intstart=file.lastIndexOf("");

this.fileName=file.substring(start+1)

java.io.FileInputStreamis=newjava.io.FileInputStream(upload);

Stringpath="D:\\upload";

//注:此处还可调用ServletActionContext.getServletContext().getRealPath(“”)设置文件的输入路径。

//指明上传的路径

java.io.FileOutputStreamout=newjava.io.FileOutputStream(path+this.fileName);

bytebu[]=newbyte[8888];

intcount=0;

count=is.read();

while(count>0)

{

out.write(bu,0,count);

str=this.SUCCESS;

}

out.close();

is.close();

returnstr;

}

publicStringexecute()throwsException

{

returnUpload();

}

}

对struts。Xml配置文件信息进行修改

<%@pagelanguage="java"contentType="text/html;charset=GB2312"%>

<%@taglibprefix="s"uri="/struts-tags"%>

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">

<html>

<h1>文件上传</h1>

<s:formaction="fileUpload"method="post"enctype="multipart/form-data">

选择要上传的图片:

<s:filename="upload"></s:file>

<br>

<s:submitvalue="上传"></s:submit>

</s:form>

</html>

相关推荐