一:jsp页面
upload.jsp
<s:form action="upload.action" method="post" enctype="multipart/form-data" theme="simple">
<s:file name="upload" label="上传文件"/>
<s:submit value="上传"/>
</s:form>
download.jsp
<s:a href="download.action">文件下载</s:a>
二:struts.xml配置
<package name="file" extends="common">
<action name="upload" class="action.FileAction" method="upload">
<result>fileupload.jsp</result>
</action>
<action name="download" class="action.FileAction" method="download">
<result type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">4096</param><!-- 输出时缓冲区的大小 -->
</result>
</action>
</package>
三:Action类
package action;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
public class FileAction {
private static final long serialVersionUID = -6269902302115912292L;
//必须的参数,参数名与表单名相同,如果一个表单名对应多个上传文件,
//则必须为数组或List
private File[] upload;
//必须的参数,格式:表单名+ContentType,表示上传文件类型
private String[] uploadContentType;
//必须的参数,格式:表单名+FileName,表示上传的文件名
private String[] uploadFileName;
public String upload() throws Exception{
File[] files = getUpload();
String realPath = ServletActionContext.getServletContext().getRealPath("/template");
if(files!=null){
for(int i=0;i<files.length;i++){
FileInputStream in = null;
FileOutputStream out = null;
try{
in = new FileInputStream(files[i]);
out = new FileOutputStream(realPath+"/"+getUploadFileName()[i]);
byte[] buf = new byte[1024];
int i;
while((i=in.read(buf))!=-1){
out.write(buf);
out.flush();
}
}catch(Exception e){
throw e;
}finally{
if(in!=null)
in.close();
if(out!=null){
out.flush();
out.close();
}
}
}
}
return SUCCESS;
}
public String download() throws Exception{
return SUCCESS;
}
public InputStream getInputStream() throws Exception{
return new FileInputStream("F:/my.xls");
}
public String getFileName(){
try {
return new String("文件.xls".getBytes(),"iso8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public File[] getUpload() {
return upload;
}
public void setUpload(File[] upload) {
this.upload = upload;
}
public String[] getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String[] getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
}