Action:
package com.fgh.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.opensymphony.xwork2.ActionSupport;
/**
* Action中一定要使用post方式 struts2标签默认是post方式
* 一定要指定enctype="multipart/form-data"
* @author ghfeng
*
*/
public class UploadAction extends ActionSupport {
private File file; // 对应真正上传的文件 和表单中name相同
private String fileFileName;// 表单中name加上FileName 固定写法 否则上传不成功 文件名不能识别
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
@Override
public String execute() throws Exception {
System.out.println("execute invoked!");
//以下全是IO操作 和struts2无关
//得到文件输入流
InputStream is = new FileInputStream(file);
//将文件转换为输出流
OutputStream os = new FileOutputStream("E:\\" + fileFileName);
byte[] buffer = new byte[1024];
int length = 0;
while (-1 != (length = is.read(buffer))) {
os.write(buffer, 0, length);
}
System.out.println("done...");
os.close();
is.close();
return SUCCESS;
}
}
jsp:
<body>
<s:form action="upload" method="post" theme="simple" enctype="multipart/form-data">
<s:file name="file"></s:file>
<br>
<s:submit></s:submit>
</s:form>
</body>