[学习笔记]Struts文件下载

来源:互联网 发布:阿里云服务器配置l2tp 编辑:程序博客网 时间:2024/06/11 18:47
Action:
public class DownloadAction extends ActionSupport { 
protected HttpServletRequest request = ServletActionContext.getRequest(); 
// HttpServletRequest request; 
private String fileName; 
public void setFileName(String fileName) 
throws UnsupportedEncodingException { 
this.fileName = ServletActionContext.getRequest().getParameter("name"); 


public String getFileName() { 
String filename = ServletActionContext.getRequest().getParameter("name"); 
System.out.println("文件名===" + filename); 
try { 
filename = new String(filename.getBytes(), "ISO8859-1"); 
} catch (UnsupportedEncodingException e) { 
e.printStackTrace(); 

return filename; 


public InputStream getInputStream() throws Exception { 
String name=this.getFileName(); 
// String realPath=ServletActionContext.getServletContext().getRealPath("/uploadImages")+ "/"+name; 路径错误 
// InputStream in=ServletActionContext.getServletContext().getResourceAsStream(realPath); 
String realPath=request.getSession().getServletContext().getRealPath("") + "/uploadList/" + name; 
System.out.println("路径 ===" + realPath); 
File file = new File(realPath); 
InputStream is = new FileInputStream(file); 
if(null==is){ 
System.out.println("Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name=\"inputName\"> tag specified for this action.检查action中文件下载路径是否正确."); 

return is; 

@Override 
public String execute() throws Exception { 

return SUCCESS; 





Struts.xml配置文件:
<action name="FileDownload" class="cn.bjjczb.wptms.action.DownloadAction"> 
<result name="success" type="stream"> 

<param 
name="contentType">application/octet-stream;charset=ISO8859-1</param> 

<param name="contentDisposition">attachment;filename="${fileName}"</param> 
<param name="bufferSize">4096</param> 
<param name="inputName">inputStream</param> 
</result> 
</action>
0 0