首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

strut2进行文件下传

2012-10-27 
strut2进行文件上传%@ taglib prefixs uri/struts-tags%!DOCTYPE HTML PUBLIC -//W3C//DTD HTML

strut2进行文件上传

<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<h1>文件上传</h1>
<s:form action="fileUpload" method="post" enctype="multipart/form-data">
选择要上传的图片:
<s:file? name="upload"></s:file>
<br>
<s:submit? value="上传"></s:submit>
</s:form>
</html>
b. 创建action类并继承ActionSupport类
package act;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
import java.sql.*;
import java.text.SimpleDateFormat;
import javax.sql.*;
import javax.swing.JOptionPane;
import javax.naming.*;
import java.util.*;
import java.util.regex.Pattern;
import org.apache.struts2.ServletActionContext;
import java.util.Date;
import java.io.*;
/*
* @author qihuasun
*? FileUploadAction类 实现文件上传
*/
public class FileUploadAction extends ActionSupport
{
? private File upload;//上传的文件
? private String fileName;
? private String contentType;
? public File getUpload()
? {
return upload;
}
public void setUpload(File upload)
{
this.upload = upload;
}
public String getFileName()
{
return fileName;
}
public void setFileName(String fileName)
? {
this.fileName = fileName;
}
public String getContentType()
{
return contentType;
}
public void setContentType(String contentType)
{
this.contentType = contentType;
}
public String Upload()throws Exception
{
String str=this.SUCCESS;
//获取文件名
String file=upload.getName();
int start = file.lastIndexOf("");
this.fileName= file.substring(start + 1)
java.io.FileInputStream is=new java.io.FileInputStream(upload);
String path="D:\\upload";
// 注:此处还可调用 ServletActionContext.getServletContext().getRealPath(“”)设置文件的输入路径。
//指明上传的路径
java.io.FileOutputStream out=new java.io.FileOutputStream(path+this.fileName);
byte bu[]=new byte[8888];
int count=0;
count=is.read();
while(count>0)
{
out.write(bu,0,count);
str=this.SUCCESS;
}
? ? out.close();
? ? is.close();
? ? return str;
}
public String execute()throws Exception
{
? ? ? ? return Upload();
}
}

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

<%@ page language="java" contentType="text/html;charset=GB2312"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<h1>文件上传</h1>
<s:form action="fileUpload" method="post" enctype="multipart/form-data">
选择要上传的图片:
<s:file? name="upload"></s:file>
<br>
<s:submit? value="上传"></s:submit>
</s:form>
</html>

热点排行