欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Struts2实现文件下载功能代码分享(文件名中文转码)

程序员文章站 2024-03-12 14:14:56
struts2文件下载功能实现代码如下所示: action文件 public class downloadaction extends actionsuppor...

struts2文件下载功能实现代码如下所示:

action文件

public class downloadaction extends actionsupport { 
/** 
* 
*/ 
private static final long serialversionuid = 5879762231742395104l; 
private string filename;//用户请求的文件名 
private string inputpath;//下载资源的路径(在struts配置文件中设置) 
public void setinputpath(string inputpath) { 
this.inputpath = inputpath; 
} 
public string getinputpath() { 
return inputpath; 
} 
public void setfilename(string filename) { 
this.filename = filename; 
} 
public string getfilename() { 
return filename; 
} 
public string downloadfile() throws exception { 
servletcontext context = servletactioncontext.getservletcontext(); 
string downloaddir = context.getrealpath("/upload"); 
string downloadfile = context.getrealpath(inputpath); 
//防止用户请求不安全的资源 
if(!downloadfile.startswith(downloaddir)) { 
return null; 
} 
return "download_success"; 
} 
/* 
* 获取输入流资源 
*/ 
public inputstream getinputstream() throws exception { 
string path = inputpath + file.separatorchar + new string(filename.getbytes("iso-8859-1"), "utf-8"); 
return servletactioncontext.getservletcontext().getresourceasstream(path); 
} 
/* 
* 获取下载时文件默认的文件名 
*/ 
public string getdownloadfilename() { 
string downloadfilename = filename; 
try { 
downloadfilename = urlencoder.encode(downloadfilename, "iso-8859-1"); 
} catch (unsupportedencodingexception e) { 
e.getmessage(); 
e.printstacktrace(); 
} 
return downloadfilename; 
} 
} 

jsp文件:

<li> 
<a href="<%=path%>/download_downloadaction_downloadfile.action?filename=dwr.jar">dwr.jar文件下在</a> 
</li> 
<li> 
<a href="<%=path%>/download_downloadaction_downloadfile.action?filename=struts2教程.pdf">struts2教程.pdf文件下在</a> 
</li> 

struts.xml:

<action name="download_*_*" class="com.wang.action.{1}" method="{2}"> 
<param name="inputpath">/upload</param> 
<!-- result type设置为stream --> 
<result name="download_success" type="stream"> 
<!-- mime类型 --> 
<param name="contenttype">application/octet-stream</param> 
<!-- inputname的值与action获取输入流资源的方法名相对应(action中定义getinputstream方法,并且返回类型为inputstream) --> 
<param name="inputname">inputstream</param> 
<!-- 设置带附件的文件 动态获取文件名(action中定义getdownloadfilename方法) --> 
<param name="contentdisposition">attachment;filename="${downloadfilename}"</param> 
<!-- 设置缓冲大小 --> 
<param name="buffersize">2048</param> 
</result> 
</action> 

以上所述是小编给大家介绍的struts2实现文件下载功能代码分享(文件名中文转码)的相关内容,希望对大家有所帮助!