JSP页面:
<form action="uploadPhoto.action" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="file" name="photoFile"></td>
<td><input type="submit" value="上传"></td>
</tr>
</table>
</form>
struts.xml配置文件:
<action name="uploadPhoto" class="com.fy.action.UploadPhotoAction">
<interceptor-ref name ="fileUploadStack"/>
<result name="success" type="redirect-action">
<param name="actionName">photo</param>
</result>
</action>
Action文件:
private File photoFile;
private String photoFileFileName;
private String photoFileContentType;
private PhotoDAO photoDAO;
private final int BUFFER_SIZE = 16 * 1024 ;
public String execute()
{
HttpServletRequest request=ServletActionContext.getRequest();
File dst=new File(ServletActionContext.getServletContext().getRealPath("\\photo")+"\\"+photoFileFileName);
copy(photoFile,dst);
return "success";
}
private void copy(File src,File dst)
{
try
{
InputStream in=null ;
OutputStream out=null ;
try
{
in=new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
out=new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while((len=in.read(buffer))>0)
{
out.write(buffer,0,len);
out.flush();
}
}
finally
{
if(null!=in)
{
in.close();
}
if(null!=out)
{
out.close();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Struts2上传文件
最新推荐文章于 2024-04-19 21:01:24 发布