struts2 file上传在简单代码

在jsp中:

<s:form action="process_task/process_task!upload" theme="simple" method="post" enctype="multipart/form-data">
<table width="80%">
<tr>
<td>上传流程</td>
<td colspan="2"><s:file name="myFile" label="上传" theme="simple" ></s:file> <input type="submit" value="上传并获取任务"/></td>
</tr>
<table>

在action 中:
@Controller
@Result(name="success",type="chain",location="process_task")
public class ProcessTaskAction extends PersistAction<ProcessTask> {
private static final long serialVersionUID = -1496120091120103L;

private static final int BUFFER_SIZE = 16*1024;
private File myFile;
private String contentType;
private String fileName;
private static String fileSite;

public void setMyFileContentType(String contentType) {
this .contentType = contentType;
}

public void setMyFileFileName(String fileName) {
this .fileName = fileName;
}

public File getMyFile() {
return myFile;
}

public void setMyFile(File myFile) {
this.myFile = myFile;
}

/**
* 上传文件的方法
* @return 返回上传文件
*/
public String upload() {
if(fileName != null && !"".equals(fileName.trim())) {
String newFileName = new Date().getTime()+getExtention(fileName);
fileSite = ServletActionContext.getServletContext().getRealPath("/uploadXml")+"/"+newFileName;
File file = new File(fileSite);
copy(myFile,file);

}
return "list";

}
/**
* 文件流的复制
* @param src 上传的源文件
* @param des 新建的文件
*/
private static void copy(File src, File des ) {
try {
InputStream in = null;
OutputStream out = null;

try {
in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
out = new BufferedOutputStream( new FileOutputStream(des), BUFFER_SIZE);
byte[] bt = new byte[BUFFER_SIZE];
int length = 0;
while((length = in.read(bt)) >0 ) {
out.write(bt,0,length);
}
} finally {
if(null != in) {
in.close();
}
if(null != out ) {
out.close();
}

}
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 获得上传文件名
* @return
*/
private static String getExtention(String fileName) {
String name= null;
if(fileName != null && !"".equals(fileName.trim())) {
int indext = fileName.lastIndexOf(".");
name = fileName.substring(indext);
}
return name;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值