-在servlet中的文件下载是通过流来实现的,在struts2中也可以
使用HttpServletResponse来实现,和以前servlet一致。注意在action执行方法中返回null。
先在WebRoot下建立download文件夹,里面放文件,这里博主放了一种名为01.jpg的图片
Action:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
public class DownloadAction {
public String execute() throws IOException{
HttpServletRequest req=ServletActionContext.getRequest();
HttpServletResponse resp=ServletActionContext.getResponse();
//获取路径
String path=req.getServletContext().getRealPath("/download");
File file=new File(path,"01.jpg");
resp.setContentLength((int)file.length());
resp.setCharacterEncoding("utf-8");
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition","attachment;filename=01.jpg");
byte[] buffer=new byte[400];
int len=0;
InputStream is=new FileInputStream(file);
OutputStream os=resp.getOutputStream();
while((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
}
os.close();
is.close();
return null;
}
}
struts.xml
<struts>
<package name="default" namespace="/" extends="struts-default">
<!-- 当action的处理结果为空的时候不用配置结果集 -->
<action name="download" class="cn.sxt.action.DownloadAction" >
</action>
</package>
</struts>
jsp
<body>
<a href="download.action">下载</a>
</body>
使用struts2的本身结果集来继续文件下载
先在WebRoot下建立download文件夹,里面放文件,这里博主放了一种名为01.jpg的图片
Action
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
import freemarker.template.utility.Execute;
public class StreamDownloadAction {
private String fileName;
public String execute(){
return Action.SUCCESS;
}
public InputStream getInputStream() throws FileNotFoundException{
HttpServletRequest req=ServletActionContext.getRequest();
String path=req.getServletContext().getRealPath("/download");
return new FileInputStream(new File(path,fileName));
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
struts.xml
<action name="streamdownload" class="cn.sxt.action.StreamDownloadAction">
<result type="stream">
<param name="contentDisposition">attachment;filename=${fileName}</param>
</result>
</action>
jsp
<body>
<a href="streamdownload.action?fileName=01.jpg">下载</a>
</body>
调试记载
- 通过合适地设置Content-disposition的值,servlet能指示浏览器是“内嵌”显示文件还是把它当作附件处理。默认是内嵌,如果上述不配置Content-disposition,那么点击链接直接内嵌图片在网页上显示,如果配置
<param name="contentDisposition">attachment;filename=${fileName}</param>
那么会作为附件处理。如下: