在 两篇我们主要说的是文件的上传,既然有上传那就有下载,那么咱们看一下struts里面是怎么个下载法!
1.写个文件下载的表单页面:
<a href="downLoad.action?fileName=1111.jpg">下载文件</a>
很简单的我们写一行就行,需要注意的是,既然你要下载的是111.jpg文件,那么你的服务器里面肯定得有一个111.jpg在里面放着才能供你下载,要不然会报错的!!!
接着我们写一下DownLoadAction里面的方法:
package org.web;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownLoadAction extends ActionSupport {
private String inputPath;
private String fileName;
private String contentType;
private InputStream inputStream;
public String excute(){
return SUCCESS;
}
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
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 InputStream getInputStream() throws FileNotFoundException {
String path=ServletActionContext.getServletContext().getRealPath(inputPath);
return new BufferedInputStream(new FileInputStream(path+"/"+fileName));
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
这个 DownLoadAction里面很简单,重要的是struts.xml配置文件里面的东西,那么请大家看:
<!-- 文件下载 -->
<action name="downLoad" class="org.web.DownLoadAction">
<param name="inputPath">/upload</param>
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">
attachment;filename="${fileName}"
</param>
<param name="bufferSize">4096</param>
</result>
</action>
这些文件上传和下载都是固定的套路,直接拿出来套上用就行!!!